JavaScript regex pattern concatenate with variable - javascript

How to create regex pattern which is concatenate with variable, something like this:
var test ="52";
var re = new RegExp("/\b"+test+"\b/");
alert('51,52,53'.match(re));
Thanks

var re = new RegExp("/\b"+test+"\b/");
\b in a string literal is a backspace character. When putting a regex in a string literal you need one more round of escaping:
var re = new RegExp("\\b"+test+"\\b");
(You also don't need the // in this context.)

With ES2015 (aka ES6) you can use template literals when constructing RegExp:
let test = '53'
const regexp = new RegExp(`\\b${test}\\b`, 'gi') // showing how to pass optional flags
console.log('51, 52, 53, 54'.match(regexp))

you can use
/(^|,)52(,|$)/.test('51,52,53')
but i suggest to use
var list = '51,52,53';
function test2(list, test){
return !((","+list+",").indexOf(","+test+",") === -1)
}
alert( test2(list,52) )

Related

How to convert regex string to regex expression? [duplicate]

So I have a RegExp regex = /asd/
I am storing it as a as a key in my key-val store system.
So I say str = String(regex) which returns "/asd/".
Now I need to convert that string back to a RegExp.
So I try: RegExp(str) and I see /\/asd\//
this is not what I want. It is not the same as /asd/
Should I just remove the first and last characters from the string before converting it to regex? That would get me the desired result in this situation, but wouldn't necessarily work if the RegExp had modifiers like /i or /g
Is there a better way to do this?
If you don't need to store the modifiers, you can use Regexp#source to get the string value, and then convert back using the RegExp constructor.
var regex = /abc/g;
var str = regex.source; // "abc"
var restoreRegex = new RegExp(str, "g");
If you do need to store the modifiers, use a regex to parse the regex:
var regex = /abc/g;
var str = regex.toString(); // "/abc/g"
var parts = /\/(.*)\/(.*)/.exec(str);
var restoredRegex = new RegExp(parts[1], parts[2]);
This will work even if the pattern has a / in it, because .* is greedy, and will advance to the last / in the string.
If performance is a concern, use normal string manipulation using String#lastIndexOf:
var regex = /abc/g;
var str = regex.toString(); // "/abc/g"
var lastSlash = str.lastIndexOf("/");
var restoredRegex = new RegExp(str.slice(1, lastSlash), str.slice(lastSlash + 1));
const regex = /asd/gi;
converting RegExp to String
const obj = {flags: regex.flags, source: regex.source};
const string = JSON.stringify(obj);
then back to RegExp
const obj2 = JSON.parse(string);
const regex2 = new RegExp(obj2.source, obj2.flags);
Requires ES6+.
You can use the following before storage of your regex literal:
(new RegExp(regex)).source
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/source
Example:
regex = /asd/
string = (new RegExp(regex)).source
// string is now "asd"
regex = RegExp(string)
// regex has the original value /asd/
let rx = RegExp.apply(RegExp, str.match(/\/(.*)\/(.*)/).slice(1));
A modified version of #PegasusEpsilon answer
StackOverflow saves the day again, thanks #4castle! I wanted to store some regex rules in a JS file, and some in a DB, combine them into an array of objects like so:
module.exports = {
[SETTINGS.PRODUCTION_ENV]: [
{
"key": /<meta name="generator"[\s\S]*?>/gmi,
"value": "",
"regex": true
},
...
]
}
Then, loop through each environment's objects and apply it to a string of text. This is for a node/lambda project, so I wanted to use ES6. I used #4castle's code, with some destructuring, and I ended up with this:
let content = body;
const regexString = replacement.key.toString();
const regexParts = /\/(.*)\/(.*)/.exec(regexString);
const {1: source, 2: flags} = regexParts;
const regex = new RegExp(source, flags);
content = content.replace(regex, replacement.value);
return content;
Works a treat!

JavaScript regex: replace variables of whole string in a sentence [duplicate]

How to create regex pattern which is concatenate with variable, something like this:
var test ="52";
var re = new RegExp("/\b"+test+"\b/");
alert('51,52,53'.match(re));
Thanks
var re = new RegExp("/\b"+test+"\b/");
\b in a string literal is a backspace character. When putting a regex in a string literal you need one more round of escaping:
var re = new RegExp("\\b"+test+"\\b");
(You also don't need the // in this context.)
With ES2015 (aka ES6) you can use template literals when constructing RegExp:
let test = '53'
const regexp = new RegExp(`\\b${test}\\b`, 'gi') // showing how to pass optional flags
console.log('51, 52, 53, 54'.match(regexp))
you can use
/(^|,)52(,|$)/.test('51,52,53')
but i suggest to use
var list = '51,52,53';
function test2(list, test){
return !((","+list+",").indexOf(","+test+",") === -1)
}
alert( test2(list,52) )

How to remove a group of characters from a string object in javascript

How to do this in a more "elegant way"?
var str = obj.property.toString(); //str value = (55.930385, -3.118425)
var remesp = str.replace(" ","");
var rempar1 = remesp.replace("(","");
var rempar2 = rempar1.replace(")",""); //rempar2 value = "55.930385,-3.118425"
Try using a regular expression character class (aka "character set") [...]:
var str = "(55.930385, -3.118425)";
str.replace(/[ ()]/g, ''); // => "55.930385,-3.118425"
In the example above, the regex /[ ()]/ matches any space or open/close parenthesis character.
The more elegant way would be using proper regex syntax in replace().
Switch ( and ) with [ and ] and use JSON.parse() to get the numbers into your new array.
var str = "(55.930385, -3.118425)".replace("(","[").replace(")","]");
var coords = JSON.parse(str);
If you need to support older browsers, you will need to use a JSON.parse shim or another solution.

Javascript regexp does not work

Test string is "page-42440233_45778105"
pattern "(page-\d+_\d+)"
Online tester(http://www.regexr.com/) successfuly finded mathc,but in browser js result is null. Why?
var re = new RegExp("(page-\d+_\d+)", "gim");
var r_array = message.match(re);
console.log(r_array);
I think this would be a better pattern
var re = /^page-\d+_\d+$/i;
It also matches the beginning (^) and end ($) of the string
message.match(re);
//=> ["page-42440233_45778105"]
You need to escape \ if you use string literal:
var message = "page-42440233_45778105";
var re = new RegExp("(page-\\d+_\\d+)", "gim");
var r_array = message.match(re);
console.log(r_array);
// => ["page-42440233_45778105"]
More preferably, use regular expression literal:
var re = /(page-\d+_\d+)/gim;
When you use a string literal, you must escape the \ :
var re = new RegExp("(page-\\d+_\\d+)", "gim");
A better solution here would be to use a regex literal :
var re = /(page-\d+_\d+)/gim
Don't use the RegExp constructor if the regular expression is constant, regex literals are much more convenient.

how to config RegExp when string contains parentheses

I'm sure this is an easy one, but I can't find it on the net.
This code:
var new_html = "foo and bar(arg)";
var bad_string = "bar(arg)";
var regex = new RegExp(bad_string, "igm");
var bad_start = new_html.search(regex);
sets bad_start to -1 (not found). If I remove the (arg), it runs as expected (bad_start == 8). Is there something I can do to make the (very handy) "new Regexp" syntax work, or do I have to find another way? This example is trivial, but in the real app it would be doing global search and replace, so I need the regex and the "g". Or do I?
TIA
Escape the brackets by double back slashes \\. Try this.
var new_html = "foo and bar(arg)";
var bad_string = "bar\\(arg\\)";
var regex = new RegExp(bad_string, "igm");
var bad_start = new_html.search(regex);
Demo
Your RegEx definition string should be:
var bad_string = "bar\\(arg\\)";
Special characters need to be escaped when using RegEx, and because you are building the RegEx in a string you need to escape your escape character :P
http://www.regular-expressions.info/characters.html
You need to escape the special characters contained in string you are creating your Regex from. For example, define this function:
function escapeRegex(string) {
return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
}
And use it to assign the result to your bad_string variable:
let bad_string = "bar(arg)"
bad_string = escapeRegex(bad_string)
// You can now use the string to create the Regex :v:

Categories

Resources