-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
  • 1,103
  • 5
  • 13
  • 29

3 Answers3

3

Regular expressions are overkill for this kind of string matching:

if (div_type.indexOf("window_") === 0) {
  // Do something
}
leepowers
  • 37,828
  • 23
  • 98
  • 129
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
  • 40,809
  • 21
  • 119
  • 172
0

You don't need a regex for that.

if( div_type.substr(0,"window_".length) == "window_")
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592