-1

I am trying to determine using javascript and regex whether a string begins with certain letters. If it's true I want it do something. I am trying to find the value "window_" in a particular string.

My code is as follows:

if (div_type.match(/^\window_/)){

}

This however is returning true when it clearly doesn't contain it.

Nuvolari
  • 961
  • 5
  • 12
  • 28

3 Answers3

3

Regular expressions are overkill for this kind of string matching:

if (div_type.indexOf("window_") === 0) {
  // Do something
}
leepowers
  • 35,484
  • 22
  • 93
  • 127
1

If you really want to go the regex route, you can use test() instead of match() /regex_pattern/.test(string)

Example:

function run(p){
   return /^window_/.test(p);
}

console.log(run("window_boo"),   // true
            run("findow_bar"));  // false

Your use:

if ( /^window_/.test(div_type) ) {
   ...
}
vol7ron
  • 35,981
  • 19
  • 104
  • 164
0

You don't need a regex for that.

if( div_type.substr(0,"window_".length) == "window_")
Niet the Dark Absol
  • 301,028
  • 70
  • 427
  • 540