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.
Related
This question already has answers here:
Javascript RegEx Not Working [duplicate]
(1 answer)
Why do regex constructors need to be double escaped?
(5 answers)
Closed 5 years ago.
I'm trying to check strings to see it they are a valid IP address:
export function checkIpIsValid(ip) {
const regex = new RegExp("^([1-2]?[0-9]{1,2}\.){3}[1-2]?[0-9]{1,2}$")
return regex.test(ip);
}
But this test is failing because it return true:
expect(checkIpIsValid("1.1.1.1")).toBe(true);
expect(checkIpIsValid("152.154.22.35")).toBe(true);
expect(checkIpIsValid("552.154.22.35")).toBe(false);
// These three are fine
// But the one below is not, it doesn't contain 4 parts so it should return false. Instead, it is returning true.
expect(checkIpIsValid("154.22.35")).toBe(false);
// Expected value to be (using ===):
// false
// Received:
// true
The thing is, when I check it on https://regex101.com/ it works fine on that case...
Don't use new RegExp(). This expects a string input, but your expression is not escaped for string. You just enclosed it in double quotes, that doesn't work.
Either use a regex literal:
function checkIpIsValid(ip) {
const regex = /^([1-2]?[0-9]{1,2}\.){3}[1-2]?[0-9]{1,2}$/;
return regex.test(ip);
}
or escape he expression properly:
function checkIpIsValid(ip) {
const regex = new RegExp("^([1-2]?[0-9]{1,2}\\.){3}[1-2]?[0-9]{1,2}$");
return regex.test(ip);
}
JS has regex literals exactly because that avoids the need for double-escaping. Use new RegExp() only for dynamically built expressions, not for fixed ones.
function checkIpIsValid(ip) {
return /^(?:\d{1,3}\.){3}\d{1,3}$/.test(ip);
}
checkIpIsValid('123.12.12'); // returns false
checkIpIsValid('123.12.12.12'); // returns true
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 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.
This question already has answers here:
Call a function if a string contains any items in an array
(3 answers)
Closed 8 years ago.
I have a string in my JavaScript code (plain JavaScript, no jQuery or any other libs involved). And also I have an array which contains characters to be found in a string. I need to check if string contains any of those characters. Of course, it could be done with temporary variable like found and array elements iteration.
But is there any way to write nice and compact code? Just in case, I use ES5 (IE9+).
I want to achieve something like
var str = "Here is the string",
chars = ['z','g'];
if (str.containsAnyOf(chars)) {
...
}
What is the best way to write that piece of code?
You can use Array.prototype.some, like this
if (chars.some(function(c) { return str.indexOf(c) !== -1; })) {
// Atleast one of the characters is present
};
Consider using regular expression:
var str = "Here is the string",
chars = ['z','g'];
// constructs the following regexp: /[zg]/
if (new RegExp("[" + chars.join('') + "]").test(str)) {
alert("Contains!");
}
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