I have this string:
var str = "jquery12325365345423545423im-a-very-good-string";
What I would like to do, is removing the part 'jquery12325365345423545423' from the above string.
The output should be:
var str = 'im-a-very-good-string';
How can I remove that part of the string using php? Are there any functions in php to remove a specified part of a string?
sorry for not including the part i have done
I am looking for solution in js or jquery
so far i have tried
var str="jquery12325365345423545423im-a-very-good-string";
str=str.replace("jquery12325365345423545423","");
but problem is numbers are randomly generated and changed every time.
so is there other ways to solve this using jquery or JS
The simplest solution is to do it with:
str = str.replace(/jquery\d+/, '').replace(' ', '');
You can use string replace.
var str = "jquery12325365345423545423im-a-very-good-string";
str.replace('jquery12325365345423545423','');
Then to removespaces you can add this.
str.replace(' ','');
I think it will be best to describe the methods usually used with this kind of problems and let you decide what to use (how the string changes is rather unclear).
METHOD 1: Regular expression
You can search for a regular expression and replace the part of the string that matches the regular expression. This can be achieved through the JavaScript Replace() method.
In your case you could use following Regular expression: /jquery\d+/g (all strings that begin with jquery and continue with numbers, f.e. jquery12325365345423545423 or jquery0)
As code:
var str="jquery12325365345423545423im-a-very-good-string";
str=str.replace("/jquery\d+/g","");
See the jsFiddle example
METHOD 2: Substring
If your code will always have the same length and be at the same position, you should probably be using the JavaScript substring() method.
As code:
var str="jquery12325365345423545423im-a-very-good-string";
var code = str.substring(0,26);
str=str.substring(26);
See the jsFiddle example
Run this sample in chrome dev tools
var str="jquery12325365345423545423im-a-very-good-string";
str=str.replace("jquery12325365345423545423","");
console.log(str)
Related
I am new to angular js . I have regex which gets all the anchor tags. My reg ex is
/<a[^>]*>([^<]+)<\/a>/g
And I am using the match function here like ,
var str = 'abc.jagadale#gmail.com'
So Now I am using the code like
var value = str.match(/<a[^>]*>([^<]+)<\/a>/g);
So, Here I am expecting the output to be abc.jagadale#gmail.com , But I am getting the exact same string as a input string . can any one please help me with this ? Thanks in advance.
Why are you trying to reinvent the wheel?
You are trying to parse the HTML string with a regex it will be a very complicated task, just use DOM or jQuery to get the links contents, they are made for this.
Put the HTML string as the HTML of a jQuery/DOM element.
Then fetch this created DOM element to get all the a elements
inside it and return their contents in an array.
This is how should be your code:
var str = 'abc.jagadale#gmail.com';
var results = [];
$("<div></div>").html(str).find("a").each(function(l) {
results.push($(this).text());
});
Demo:
var str = 'abc.jagadale#gmail.com';
var results = [];
$("<div></div>").html(str).find("a").each(function(l) {
results.push($(this).text());
});
console.log(results);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You need to capture the group inside the anchor tags. The regular expression already matches the inner group ([^<]+) But, when matching there are different ways to extract that inner text.
When using the Match function it will return an array of matched elements, the first one, will match the whole regular expression and the following elements will match the included groups in the regular expression.
Try this:
var reg = /<a[^>]*>([^<]+)<\/a>/g
reg.exec(str)[1]
Also the match function will return an array only if the g flag is not present.
Check https://javascript.info/regexp-groups for further documentation.
Brief
Don't use regex for this. Regex is a great tool, don't get me wrong, but it's not what you're looking for. Regex cannot properly parse HTML and should only be used to do so if it's a limited, known set of HTML.
Try, for example, adding content:">" to your style attribute. You'll see your pattern now fails or gives you an incorrect result. I don't like to use this quote all the time, but I think it's necessary to use it in this case:
Some people, when confronted with a problem, think "I know, I'll use
regular expressions." Now they have two problems.
Use builtin functions. jQuery makes this super easy to accomplish. See my Code section for a demonstration. It's way more legible than any regex variant.
Code
DOM from page
The following snippet gets all anchors on the actual page.
$("a").each(function() {
console.log($(this).text())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
abc.jagadale#gmail.com
abc2.jagadale#gmail.com
DOM in string
The following snippet gets all anchors in the string (converted to DOM element)
var s = `email3#domain.com
email4#domain.com`
$("<div></div>").html(s).find("a").each(function() {
console.log($(this).text())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
email1#domain.com
email2#domain.com
Given the use case of parsing a string, instead of having an actual DOM to work with, it does seem like regex is the way to go, unless you want to load the HTML into a document fragment and parse that.
One way to get all of your matches is to make use of split:
var htmlstr = "<p><a href='url'>asdf#bsdf.com</a></p>"
var matches = htmlstr.split(/<a.+?>([A-Za-z.#]+)<\/a>/).filter((t, i) => i % 2)
Using a regex with split returns all of the matches along with the text around them, then filtering by index % 2 will pare it down to just the regex matches.
I'm not using JQuery, so I don't think that's causing the trouble. I first ran into this using the iOS automation tool and then went to verify it using JSFiddle. If anyone can show me a way around this it would fantastic.
var str = "<'pass!23$'>";
var str1 = str.replace("<'pass!23$'>", "'pass!23$'");
var str2 = str.replace("<'pass!23$'>", "'pass!23$a'");
Here's the fiddle: http://jsfiddle.net/adUtw/
This is really confusing me!
If you look at the documentation for string.replace at MDN, you'll notice that $ alone has some special meanings for replace. Therefore, if you want to insert a $ you need to use $$.
Your replace statement would then look like:
var str1 = str.replace("<'pass!23$'>", "'pass!23$$'");
You can verify it is working by updating the Fiddle.
$ is interpreted in a special way when it appears in the second argument to replace.
It is used to refer to regex groups defined in the first argument:
'abc'.replace('(b)', 'XY$1Z') === 'aXYbZc'
And $' is interpreted as the portion of the string that follows the matched substring.
To use a $ in the second argument, escape it by saying $$.
var str1 = str.replace("<'pass!23$'>", "'pass!23$$'");
I can't replace the substring in a string:
var source = "div.col-md-4.fields:visible:eq(0) div.panel-body select:eq(0)";
var modified = source.replace(/visible:eq(0)/g, "1234");
I wonder why does modified have the same value as source?
You should not use regular expressions here but a simple string replace function. It will run faster and regular expressions were not made for simple tasks like this as they will run slightly slower than the simple replace function. Using regular expressions here is like using a nuke to open a water bottle, rather prefer simplicity, if a developer sees this code he will like the simplicity.
Change your second line to this one:
var modified = source.replace("visible:eq(0)", "1234");
You need to escape the brackets
var source = "div.col-md-4.fields:visible:eq(0) div.panel-body select:eq(0)";
var modified = source.replace(/visible:eq\(0\)/g, "1234");
console.log(source);
console.log(modified);
You just need to escape your chars like this Demo: http://jsfiddle.net/cvW24/1/
hope rest help the cause :)
if you keen:
Need to escape a special character in a jQuery selector string
http://api.jquery.com/category/selectors/
code
var source = "div.col-md-4.fields:visible:eq(0) div.panel-body select:eq(0)";
var modified = source.replace(/visible:eq\(0\)/g, "1234");
alert(modified);
Because your regular expression does not match the string. You need to escape the parenthesis.
var modified = source.replace(/visible:eq\(0\)/g, "1234");
There is a part in my string from, to which I would like to replace to an another string replace_string. My code should work, but what if there is an another part like the returned substring?
var from=10, to=17;
//...
str = str.replace(str.substring(from, to), replace_string);
For example:
from=4,to=6
str = "abceabxy"
replace_string = "zz"
the str should be "abcezzxy"
What you want to do is simple! Cut out and replace the string. Here is the basic tool, you need scissor and glue! Oops I mean string.Split() and string.Replace().
How to use?
Well I am not sure if you want to use string.Split() but you have used string.Replace() so here goes.
String.Replace uses two parameters, like this ("one", "two") what you need to make sure is that you are not replacing a char with a string or a string with a char. They are used as:
var str="Visit Microsoft!";
var n=str.replace("Microsoft","W3Schools");
Your code:
var from=10, to=17;
//...
var stringGot = str.replace(str.substring(from, to), replace_string);
What you should do will be to split the code first, and then replace the second a letter! As you want one in your example. Thats one way!
First, split the string! And then replaced the second a letter with z.
For String.Replace refer this: http://www.w3schools.com/jsref/jsref_replace.asp
For String.SubString: http://www.w3schools.com/jsref/jsref_substring.asp
For String.Split: http://www.w3schools.com/jsref/jsref_split.asp
Strings are immutable. This means they do not change after they are first instantiated. Every method to manipulate a string actually returns a new instance of a string. So you have to assign your result back to the variable like this:
str = str.replace(str.substring(from, to), replace_string);
Update: However, the more efficient way of doing this in the first place would be the following. it is also less prone to errors:
str = str.substring(0, from) + replace_string + str.substring(to);
See this fiddle: http://jsfiddle.net/cFtKL/
It runs both of the commands through a loop 100,000 times. The first takes about 75ms whereas the latter takes 20ms.
I need to capture the price out of the following string:
Price: 30.
I need the 30 here, so I figured I'd use the following regex:
([0-9]+)$
This works in Rubular, but it returns null when I try it in my javascript.
console.log(values[1]);
// Price: 100
var price = values[1].match('/([0-9]+)$/g');
// null
Any ideas? Thanks in advance
Try this:
var price = values[1].match(/([0-9]+)$/g);
JavaScript supports RegExp literals, you don't need quotes and delimiters.
.match(/\d+$/) should behave the same, by the way.
See also: MDN - Creating a Regular Expression
Keep in mind there are simpler ways of getting this data. For example:
var tokens = values[1].split(': ');
var price = tokens[1];
You can also split by a single space, and probably want to add some validation.
Why don't you use this?
var matches = a.match(/\d+/);
then you can consume the first element (or last)
my suggestion is to avoid using $ in the end because there might be a space in the end.
This also works:
var price = values[1].match('([0-9]+)$');
It appears that you escaped the open-perens and therefore the regex is looking for "(90".
You don't need to put quotes around the regular expression in JavaScript.