-1

As you can see from the example, I passed a variable called snoop to coincide for the word argument in the function. I want whatever value I put in for word to be put under the same type of meta-characters. The problem is that every time I try to put meta-charaters around word ie. ( var snoop = new RegExp( /\bword/, 'gi' )) for example, it doesn't work. What would be the proper way to code this?

var gill = ['airplane','airport','apple','ball']

function auto (word, array){
    var geo = array.join(" ")

    var snoop = new RegExp(word, 'gi' )

    var gip = geo.match(snoop)

    console.log(gip)

}

auto("ai", gill)
Bo Borgerson
  • 1,386
  • 10
  • 20
Kai
  • 25
  • 4

1 Answers1

0

The "word" in new RegExp( /\bword/, 'gi' )) is just the literal string "word". It's not a reference to your variable word. You can create a new RegExp object using a string, which may be built up using concatenation.

Keep in mind that you'll need to use double backslashes, because a single backslash in a string literal begins an escape sequence. For example "\b" is the backspace character. The special escape sequence "\\" produces a backlash, which is what you want in your regular expression.

Here is an example that produces what I think you were trying to achieve:

var snoop = new RegExp("\\b" + word, "gi")

You can use this technique to interpolate a variable into any portion of a regular expression:

// Capture one or more of the characters in `validCharacters` after an equals-sign.
new RegExp("=([" + validCharacters + "]+)")
Bo Borgerson
  • 1,386
  • 10
  • 20
  • Can you please go deeper into why im using double slashes? I would also like to learn the general format for this so I can be free to add as many meta-characters as id like wwhat if it wanted to do this : /new RegExp(\b\w^[word]$/) for example. What would be the syntax? – Kai Jun 16 '16 at 00:19
  • so this double backslash goes for \B,\w,\s as well? Thanks for your help btw – Kai Jun 16 '16 at 00:39
  • Yep! The double-backslash is actually just to _produce a backslash_. – Bo Borgerson Jun 16 '16 at 00:40