JS replacing all occurrences of string using variable [duplicate] - javascript

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

Related

JS URL regex, allow only urls and empty string [duplicate]

This question already has answers here:
Regular expression which matches a pattern, or is an empty string
(5 answers)
Closed 2 years ago.
I have the following regext:
var regex = /^(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/g;
function test() {
alert(regex.test(document.getElementById("myinput").value));
}
I want to allow url or empty string. regex solution please
How do I allow empty in this case?
https://jsfiddle.net/6kptovwc/2/
Thanks
Add an alternation with empty string (I've simplified a bit your regex):
^((?:https?:\/\/)?(?:www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b[-a-zA-Z0-9#:%_\+.~#?&\/=]*|)$
or
^((?:https?:\/\/)?(?:www\.)?[-\w#:%.+~#=]{2,256}\.[a-z]{2,6}\b[-\w#:%+.~#?&\/=]*|)$
Demo & explanation
Just add OR(||) condition
function test() {
const elm = document.getElementById("myinput")
alert(elm.value === '' || regex.test(elm.value));
}
^$|pattern
var regex = /^$|(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/g;

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.

JavaScript RegExp concatinating variable [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Why this javascript regex doesn't work?
(1 answer)
Closed 4 years ago.
Trying to replace all a's in the string ignoring the case.
str = "All a's will be replaced";
str.replace(/a/gi, 'Aa');
As expected, the above line of code produces Aall Aa's will be replAaced
But,
regExp = new RegExp('/a/gi');
str.replace(regExp, 'Aa');
the above line with the use of RegExp pattern produces original string All a's will be replaced
How to achieve expected result?

How to use dynamic variable between regular expression [duplicate]

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.

Global replace using variable [duplicate]

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.

Categories

Resources