0

Trying to find folders that start with variables that are NOT case sensitive

var varname = ("BUI")
var stringMatch = "\\" + varname + "\\b";
if (FolderItems[i].name.match(stringMatch)) {
//do script
}

I find Regex pretty confusing, I know varname = \\\BUI\\\b, but what do I need to find a folder that begins with that variable? I'd like this to find a folder called 'Building_v02'

Mario S
  • 11,715
  • 24
  • 39
  • 47
user1739337
  • 113
  • 1
  • 11

4 Answers4

0
 if (FolderItems[i].name.match("^[BUI]")) {
  //do script
 }

^ mean that the string should start with 'BUI'

  • Actually it means the string should start with either `B`, `U`, or `I`. For a string starting with `BUI` you'd have to to `^(BUI)` (capturing) or `^(?:BUI)` (non-capturing). – Benedikt Deicke Jan 19 '13 at 08:48
0

In the JavaScript regexp syntax, ^ is the anchor for the start of the string. Case insensitivity is indicated separately with the i flag:

var varname = "BUI";
var re = new RegExp("^" + varname, "i");
if (re.test(FolderItems[i].name)) {
    // do script
}

However, you should escape the string if it could contain any undesirable regexp metacharacter.

Also note that you may not have to use a regexp:

var varname = "BUI".toLowerCase();
if (FolderItems[i].name.toLowerCase().indexOf(varname) === 0) {
    // do script
}

To actually iterate over the array of items:

for (var i = 0; i < FolderItems.length; i++) {
    // ...
}
Community
  • 1
  • 1
PleaseStand
  • 31,641
  • 6
  • 68
  • 95
0

You can easily try in your browsers console. I'd say that you're better of using substring when you're matching the start of a string.

var matchFor = "BUI";
var folders = ["Building_v02","Building_v03", "unmatched"];
folders.filter(function(folder){
     return folder.substring(0,3).toLowerCase()===(matchFor.toLowerCase());
  }).forEach(function(value){
     console.log(value)
  });

This will not work in older browsers unless you add filter and forEach, for example using underscore.js

try-catch-finally
  • 7,436
  • 6
  • 46
  • 67
iwein
  • 25,788
  • 10
  • 70
  • 111
  • Modified your code: extracted search term into `matchFor` and using `toLowerCase()` as the OP wants to match case insensitive. *"[...] start with variables that are NOT case sensitive"* – try-catch-finally Jan 19 '13 at 09:25
0
var varname = "BUI";
var stringMatch = '^' + varname + '\\b';

if ( FolderItems[i].name.match( RegExp( stringMatch, 'i' ) ) {
    //do script
}

You can pass a string to match as you were doing, but if you pass in a RegExp object you can supply a second argument, i, which indicates that you want a case-insensitive match.

Regular Expressions MDN

MikeM
  • 13,156
  • 2
  • 34
  • 47