3

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

1 Answers1

4

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.

Lix
  • 47,311
  • 12
  • 103
  • 131
  • 1
    For `RegExp` constructor all escape collections should be escaped with extra backslash (``\\``). – VisioN Nov 24 '14 at 09:48
  • @Bala - I know :/ I know... It actually happened the other way around... I posted the answer first then realized that it's probably a duplicate. – Lix Nov 24 '14 at 09:56
  • @Bala - [it's not such a bad thing though...](http://blog.stackoverflow.com/2010/11/dr-strangedupe-or-how-i-learned-to-stop-worrying-and-love-duplication/). – Lix Nov 24 '14 at 09:57
  • @VisioN- I did miss it :) Thanks for your feedback! Corrections and reference added. – Lix Nov 24 '14 at 10:05
  • this answer is not working.can you share the another answers with full coding – Peter Abraham Nov 24 '14 at 12:44
  • @PeterAbraham- "not working" is not specific enough. If you have a specific problem with the solution, please describe it here so that we may help you appropriately. – Lix Nov 24 '14 at 12:46