Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variable inside the regular expression in javascript [duplicate]

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

like image 304
Peter Abraham Avatar asked Aug 15 '26 18:08

Peter Abraham


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

like image 91
Lix Avatar answered Aug 17 '26 08:08

Lix