#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2002
    Posts
    10
    Rep Power
    0

    Find instances of word not encapsulated by brackets


    I'm looking to find all instances of a word, excluding those instances that are encapsulated by brackets (eg []). For example, if this is my string "This is a word but not this [Image:This-is-a-word.jpg] and another word but not wordless" and I'm searching for the string "word". I'm totally stuck on the bracket situation. I thought maybe lookaheads might help, but I just can't get it. Any help would be appreciated. Thanks!
  2. #2
  3. Transforming Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,191
    Rep Power
    9398
    Search for non-bracketed text followed by bracketed text, and only replace the words in the first part.
    Code:
    var string = "xx[xxx]x[x][x]x[xx]xx";
    var search = /x/g;
    var replace = function($0) { return "y"; };
    
    string = string.replace(/([^[]+)((?:\[[^\]]+\])*)/g, function($0, $1, $2) {
    	return $1.replace(search, replace) + ($2 || "");
    });
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2002
    Posts
    10
    Rep Power
    0
    Thanks @requinix. Worked great!!

IMN logo majestic logo threadwatch logo seochat tools logo