This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 6 years ago.
Hi I have a problem here. I am trying to replace all instances of + character in a string using javascript. What happens is that only the first instance is being changed.
Here is my code:
var keyword = "Hello+Word%+";
keyword = keyword.replace("+", encodeURIComponent("+"));
alert(keyword);
The output is Hello%2BWord%+ when it should be Hello%2BWord%%2B because there are 2 instances of +.
You can check this on : http://jsfiddle.net/Wy48Z/
Please help. Thanks in advance.
You need the global flag.
Fixed for you at http://jsfiddle.net/rtoal/Wy48Z/1/
var keyword = "Hello+Word%+";
keyword = keyword.replace(/\+/g, encodeURIComponent("+"));
alert(keyword);
The javascript regex, which is done by putting the expresison inbetween two forward slashes like: /<expression/
If you want to replace all, simply append a g after the last one like:
/<expression/g
In your case, it would be /\+/g
The cross-browser approach is to use a regexp with the g (global) flag, which means "process all matches of the pattern, not just the first":
keyword = keyword.replace(/\+/g, encodeURIComponent("+"));
Notice I prefix the plus sign with a backslash because it would otherwise have the special meaning of "match one or more of the preceding thing".
Related
This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 6 years ago.
I have string which contains some date and some comma separated values like this
var a = "1,13,20160308,200500000012016,10,Pending,01-02-2016,1|#|1,13,20160418,200500000012016,10,Pending,08-03-2016,1|#|1,13,20160623,200500000012016,10,Pending,18-04-2016,1|#|1,13,20160803,200500000012016,10,Pending,23-06-2016,1|#|1,13,20160912,200500000012016,10,Pending,03-08-2016,1|#|1,13,20161022,200500000012016,10,Pending,12-09-2016,1|#|1,13,20161129,200500000012016,10,Pending,22-10-2016,1|#|1,13,20170110,200500000012016,10,Pending,29-11-2016,1|#|1,13,20170215,200500000012016,10,Pending,10-01-2017,1|#|15-02-2017 APPEARANCE"
regular expression: /(.)*?01-02-2016(.)*?\|\#\|/igm
By using this regular expression i can able to delete unnecessary part in string.
Now i want to change 03-08-3016 (date) dynamically. If i use
var date = "01-02-2016"
var reg = /(.)*?${date}(.)*?\|\#\|/igm;
If you pring reg in console.log you will get like this below
console.log(reg) ----> output: '/(.)?01-02-2016(.)?|#|/igm'
Expected Final output will delete upto 01-02-2016,1|#|
Use this.
var regex="(.)*?01-02-2016(.)*?\\|\\#\\|";
var rx=new RegExp(regex,"igm");
console.log(rx);
//Then when do you want to change,
regex=regex.replace("01-02-2016","03-02-2016");
rx=new RegExp(regex,"igm");
console.log(rx);
JavaScript have 2 methods to make a Regular Expression.
1. write it in slashes //
2. Make from string using new RexExp(string);
If you make it from string, you can give the constraint(" global, incase, etc.") as the second parameter as i did in the above.
and also you have to double escape (\) the escape characters.
This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Fastest method to replace all instances of a character in a string [duplicate]
(14 answers)
Closed 1 year ago.
I'm trying to do replace in JavaScript using:
r = "I\nam\nhere";
s = r.replace("\n"," ");
But instead of giving me
I am here
as the value of s,
It returns the same.
Where's the problem??
As stated by the others the global flag is missing for your regular expression. The correct expression should be some thing like what the others gave you.
var r = "I\nam\nhere";
var s = r.replace(/\n/g,' ');
I would like to point out the difference from what was going on from the start.
you were using the following statements
var r = "I\nam\nhere";
var s = r.replace("\n"," ");
The statements are indeed correct and will replace one instance of the character \n. It uses a different algorithm. When giving a String to replace it will look for the first occurrence and simply replace it with the string given as second argument. When using regular expressions we are not just looking for the character to match we can write complicated matching syntax and if a match or several are found then it will be replaced. More on regular expressions for JavaScript can be found here w3schools.
For instance the method you made could be made more general to parse input from several different types of files. Due to differences in Operating system it is quite common to have files with \n or \r where a new line is required. To be able to handle both your code could be rewritten using some features of regular expressions.
var r = "I\ram\nhere";
var s = r.replace(/[\n\r]/g,' ');
use s = r.replace(/\\n/g," ");
Get a reference:
The "g" in the javascript replace code stands for "greedy" which means the replacement should happen more than once if possible
The problem is that you need to use the g flag to replace all matches, as, by default, replace() only acts on the first match it finds:
var r = "I\nam\nhere",
s = r.replace(/\n/g,' ');
To use the g flag, though, you'll have to use the regular expression approach.
Incidentally, when declaring variables please use var, otherwise the variables you create are all global, which can lead to problems later on.
.replace() needs the global match flag:
s = r.replace(/\n/g, " ");
It's working for me:
var s = r.split('\\n').join(' ');
replaceAll() is relative new, not supported in all browsers:
r = "I\nam\nhere";
s = r.replaceAll("\n"," ");
You can use:
var s = r.replace(/\n/g,' ').replace(/\r/g,' ');
because diferents SO use diferents ways to set a "new line", for example: Mac Unix Windows, after this, you can use other function to normalize white spaces.
Just use \\\n to replace it will work.
r.replace("\\\n"," ");
The solution from here worked perfect for me:
r.replace(/=(\r\n|\n|\r)/gm," ");
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I match multiple occurrences with a regex in JavaScript similar to PHP’s preg_match_all()?
I am trying to parse an xml document like this:
var str = data.match("<string>" + "(.*?)" + "</string>");
console.log(str);
I want to get all the elements between the [string] in an array but for some reason, it only returns the first string element found. Im not good with regular expressions so Im thinking this is just a small regex issue.
You want it to be global g
var str="<string>1</string><string>2</string><string>3</string>";
var n=str.match(/<string>(.*?)<\/string>/g);
//1,2,3
You have to form the RegEx adding a g to it like
/Regex/g
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript Split without losing character
I have a string:
"<foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar>"
I want to separate all instances of "abcdefg" into an array like this:
["<foo>abcdefg</bar>", "<foo>abcdefg</bar>", "<foo>abcdefg</bar>", "<foo>abcdefg</bar>"];
I try:
var str="<foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar>";
var Array_Of_FooBars = str.split("</bar>");
alert(Array_Of_FooBars);
But it returns:
["<foo>abcdefg", "<foo>abcdefg", "<foo>abcdefg", "<foo>abcdefg",]
It is removing the separator ''. I don't want that.
How can I use split and not lose the separators from the string?
Thanks.
Ken
Try this. It's not a perfect solution, but it should work in most cases.
str.split(/(?=<foo>)/)
That is, split it in the position before each opening tag.
EDIT: You could also do it with match(), like so:
str.match(/<foo>.*?<\/bar>/g)
It seems that you would most likely want to use match:
var s = "<foo>abcd1efg</bar><foo>abc2defg</bar><foo>abc3defg</bar><foo>abc4defg</bar>"
s.match(/(<foo>.+?<\/bar>)/g)
// =>["<foo>abcd1efg</bar>", "<foo>abc2defg</bar>", "<foo>abc3defg</bar>", "<foo>abc4defg</bar>"]
You could just iterate over a simple regular expression and build the array that way:
var x = new RegExp('<foo>(.*?)</bar>', 'ig'),
s = "<foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar>",
matches = [];
while (i = x.exec(s)) {
matches.push(i[0]);
}
Just realized using String.match() would be better; this code would be more useful for matching the contents inside the tags.
Use positive lookahead so that the regular expression asserts that the special character exists, but does not actually match it:
string.split(/<br \/>(?=&#?[a-zA-Z0-9]+;)/g);
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript replace all / with \ in a string?
I have a date='13/12/2010' I want to replace this '/' to '_' or something else.
I read this But I do not know how can that applied for my case .
Use a global RegEx (g = global = replace all occurrences) for replace.
date = date.replace(/\//g, '_');
\/ is the escaped form of /. This is required, because otherwise the // will be interpreted as a comment. Have a look at the syntax highlighting:
date = date.replace(///g, '_');
One easiest thing :)
var date='13/12/2010';
alert(date.split("/").join("_")); // alerts 13_12_2010
This method doesn't invoke regular expression engine and most efficient one
You can try escaping the / character like this -
date.replace( /\//g,"_");