How to dynamically create regex to use in .match Javascript? [duplicate] - javascript

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 8 years ago.
I need to dynamically create a regex to use in match function javascript.
How would that be possible?
var p = "*|";
var s = "|*";
"*|1387461375|* hello *|sfa|* *|3135145|* test".match(/"p"(\d{3,})"s"/g)
this would be the right regex: /\*\|(\d{3,})\|\*/g
even if I add backslashes to p and s it doesn't work. Is it possible?

RegExp is your friend:
var p = "\\*\\|", s = "\\|\\*"
var reg = new RegExp(p + '(\\d{3,})' + s, 'g')
"*|1387461375|* hello *|sfa|* *|3135145|* test".match(reg)
The key to making the dynamic regex global is to transform it into a RegExp object, and pass 'g' in as the second argument.
Working example.

You can construct a RegExp object using your variables first. Also remember to escape * and | while forming RegExp object:
var p = "*|";
var s = "|*";
var re = new RegExp(p.replace(/([*|])/g, '\\$1')
+ "(\\d{3,})" +
s.replace(/([*|])/g, '\\$1'), "g");
var m = "*|1387461375|* hello *|sfa|* *|3135145|* test".match(re);
console.log(m);
//=> ["*|1387461375|*", "*|3135145|*"]

Related

Replace string with a value using RegExp object in javascript [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Remove all special characters with RegExp
(10 answers)
Closed 3 years ago.
Maybe I forgot how RegExp works but I tried to replace a text with empty values.
I have text like: this is a blabla (32332) [XAML] and I want to remove [] and ().
I want to do using RegExp object. In javascript, I'm doing like:
var obj = "this is a blabla (32332) [XAML]";
var patt1 = "[\(\)\]\[]";
var regObj = new RegExp(patt1, "gi");
obj = obj.replace(regObj, "");
console.log(obj);
The result is still same this is a blabla (32332) [XAML] means nothing is replaced.
Where is my mistake ? Here's fiddle: https://jsfiddle.net/weak5ub3/
You can use capture group and replace
var obj = "this is a blabla (32332) [XAML]";
var patt1 = /\(([^)]*)\)|\[([^\]]*)\]/gi;
obj = obj.replace(patt1, "$1$2");
console.log(obj)
If you want to remove [] and () irrespective of where they are, they are balanced or not, than you can simply use
[\]()\[]+
Regex Demo
using RegExp object, you need is to escape special characters with \\ when you want to use regexp object
var obj = "this is a blabla (32332) [XAML]";
var patt1 = new RegExp("\\(([^)]*)\\)|\\[([^\\]]*)\\]", "gi");
obj = obj.replace(patt1, "$1$2");
console.log(obj)
var pat2 = new RegExp("[\\]()\\[]+", "gi")
var secondObj = obj.replace(pat2, "$1$2")
console.log(secondObj)

insert variable via forEach into regex expression [duplicate]

This question already has answers here:
Use dynamic (variable) string as regex pattern in JavaScript
(8 answers)
Closed 4 years ago.
As you can see below, I'm trying to count how many times a character in string J occurs in string S. The only issue is I can't put the argument o in the forEach loop into the regex expression as shown in the console.log.
var numJewelsInStones = function(J, S) {
let jArr = J.split('');
let sArr = S.split('');
jArr.forEach(o=>{
console.log(S.replace(/[^o]/g,"").length);
})
};
numJewelsInStones("aA", "aAAbbbb");
You can create regular expression with constructor function where you pass string parameters:
new RegExp('[^' + o + ']', 'g')
Your replace logic might look like:
S.replace(new RegExp('[^' + o + ']', 'g'), '')

Is there a way to replace a string in a text without spaces? [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 6 years ago.
Is there a way to replace something like this:
testHoraciotestHellotest
And replace the 'test' word via javascript, I've tried with the .replace() function but it didn't work
str.replace() also accepts regular expressions, so you can use /test/g to match all instances of 'test' in the string.
var str = "testHoraciotestHellotest";
var res = str.replace(/test/g, "replaced");
console.log(res);
use g to make a global replace to the string
var str = "testHoraciotestHellotest";
var res = str.replace(/test/g, "word");
console.log(res);
It's simple.
var str = "testHoraciotestHellotest";
var res = str.replace("test", "test1");
console.log(res);
If you want to replace all occurances of 'test' rather than just one, use the following trick instead:
var res = str.split("test").join ("test1");

Javascript regex test from variable [duplicate]

This question already has answers here:
Backslashes - Regular Expression - Javascript
(2 answers)
Closed 6 years ago.
I have an problem with constructing regex from variable.
var a = '.playlist-item:nth-child(2n+1)';
var selector = /.playlist-item:nth-child\(2n\+1\)/g;
var s = '.playlist-item:nth-child\(2n\+1\)';
console.log(selector.test(a))//true
var reg = new RegExp(s,"g");
console.log(reg.test(a) )//false
Second is false because I have string quotes around it (I think), how do I construct regexp from string?
https://jsfiddle.net/eq3eu2e8/1/
For a string you have to use double backslashes if you want to include them in the string:
var a = '.playlist-item:nth-child(2n+1)';
var selector = /.playlist-item:nth-child\(2n\+1\)/g;
var s = '.playlist-item:nth-child\\(2n\\+1\\)';
console.log(selector.test(a)); //true
var reg = new RegExp(s,"g");
console.log(reg.test(a)); //false

JavaScript Find and replace with variable in regular expression [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Regular Expression Pattern With A Variable
function function1() {
var key = "name";
var sample = "param.name['key'] = name; param.name[i] = 1000; param.name1[i] = name1;";
var result = result.replace(/param.<<name>>\[(\d+)\]/g, 'parameter[prefix_$1]');
}
Expected result: parameter['prefix_key'] = name; parameter['prefix_i'] = 1000;
I cant add variable key into the replace function in regular expresssion.
Please help how to construct the regular expression in replace
You can make a regex out of a string by making a RegExp object:
var regex = new RegExp("param\\." + name + "\\[(\d+)\\]", "g")
var result = result.replace(regex, 'parameter[prefix_$1]');

Categories