Global replace using variable [duplicate] - javascript

This question already has answers here:
Fastest method to replace all instances of a character in a string [duplicate]
(14 answers)
Closed 7 years ago.
In JavaScript I can uses a regex to replace tex:
var textSearch = "10";
var textReplace = "2";
var c = alayer.textItem.contents
c = c.replace(new RegExp(textSearch, "g"),textReplace);
alert(c);
text strings of "10" gets replaced with "2". Huzzah!
However, I was unable to do a global replace without a new RegExp constructor I got into a mess.
c = c.replace(textSearch, textReplace); //2 10 10
I tried various iterations of /g and "g" to no avail.
Do you have to uses regxEx in the form of new regExp() when using variables, or am I missing a trick? Reginald X. Pression where are you?? I need your help!

Indeed, normally you have to use a RegExp to replace more than once instance. There is however a non-standard third "flags" argument to replace() that should achieve a global replace even if you use a plain string as the search expression: c = c.replace('needle', haystack, 'g'); See the MDN reference. Note though that this extra argument is not supported in e.g. Chrome, so the RegExp approach is the best.

Related

Transform a "Regex" string to actual Regex in Javascript [duplicate]

This question already has answers here:
Converting user input string to regular expression
(14 answers)
Closed 3 years ago.
I need to pass a regular expression in a validation function in my code that can only be set by an administrator in a back office platform as a string (e.g. '/^(?:\d{8}|\d{11})$/'). After it is passed I need to take this string and transform it into an actual javascript regex in order to use it.
const validator = (regex, value) => {
if (value && regex.test(value)) {
return 'Yeah!!';
}
return null;
};
So I need this '/^(?:\d{8}|\d{11})$/' to be like this /^(?:\d{8}|\d{11})$/.
You can initialize a regex with the RegExp method (documentation on MDN):
The RegExp constructor creates a regular expression object for matching text with a pattern.
const regex2 = new RegExp('^(?:\\d{8}|\\d{11})$');
console.log(regex2); // /^(?:\d{8}|\d{11})$/
You could instantiate the RegExp class and use it in two ways:
First:
new RegExp('<expression>').test(...)
Second:
/<expression>/.test(...)
Both ways will create an RegExp instance.
When to use one over the other?
Using the new RegExp way you can pass variables to the expression, like that:
new RegExp('^abc' + myVar + '123$');
Which you can't do using the second way.

Use variable inside the regular expression in javascript [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 8 years ago.
My code:
var string = "I put putty on the computer. putty, PUT do I"
var uniques = {};
var result = (string.match(/\b\w*put\w*\b/ig) || []).filter(function(item) {
item = item.toLowerCase();
return uniques[item] ? false : (uniques[item] = true);
});
document.write( result.join(", ") );
Here i want pass a variable inside the expression
here i have pass a value 'put' and get answer. But i have to use variable for this value.
I have tried string.match(/\b\w*{+put+}\w*\b/ig
Can you share your answers
You should create a specific Regular Expression object to use with the .match() function. This way you can create your regex with a string and insert the variable when creating it:
var changing_value = "put";
var re = new RegExp("\\b\\w*" + changing_value + "\\w*\\b", "ig");
Note that the ignore case (i) and global (g) modifiers are specified as the second parameter to the RegExp constructor instead of part of the actual expression. Also that you need to escape the \ character inside the constructor because \ is also an escape character in strings.
Another thing to note is that you don't need the /delimiters/ at the start and end of the expression when using the Regexp constructor.
Now you can use the Regexp object in your call to .match():
string.match( re )
As a final note, I don't recommend that you use the name string as a variable name... As you can see from the syntax highlighting, string is a reserved word and it is not recommended to use names of built-in types for variable names as they may cause confusion.

JS replacing all occurrences of string using variable [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 9 years ago.
I know that str.replace(/x/g, "y")replaces all x's in the string but I want to do this
function name(str,replaceWhat,replaceTo){
str.replace(/replaceWhat/g,replaceTo);
}
How can i use a variable in the first argument?
The RegExp constructor takes a string and creates a regular expression out of it.
function name(str,replaceWhat,replaceTo){
var re = new RegExp(replaceWhat, 'g');
return str.replace(re,replaceTo);
}
If replaceWhat might contain characters that are special in regular expressions, you can do:
function name(str,replaceWhat,replaceTo){
replaceWhat = replaceWhat.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var re = new RegExp(replaceWhat, 'g');
return str.replace(re,replaceTo);
}
See Is there a RegExp.escape function in Javascript?
The third parameter of flags below was removed from browsers a few years ago and this answer is no longer needed -- now replace works global without flags
Replace has an alternate form that takes 3 parameters and accepts a string:
function name(str,replaceWhat,replaceTo){
str.replace(replaceWhat,replaceTo,"g");
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

replace '\n' in javascript [duplicate]

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," ");

javascript - How to do replaceAll? [duplicate]

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".

Categories

Resources