简体   繁体   中英

How to use a Regular Expression in JavaScript which contains special characters

Sorry, probably being dumb this morning, but I don't know much about regular expressions, but have created something I want to use with https://regex101.com/

But... I can't use the code they suggest in Javascript without escaping it first.

Here's the regex: (?<=color:\\s)([az]+)

Which, does what I want (matching a word after color: in a CSS file)

But, the code they suggest to use in JS is:

var re = /(?<=color:\s)([a-z]+)/g; 
var str = ' color: black';
var m;

while ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    // View your result using the m-variable.
    // eg m[0] etc.
}

The first line, won't work, so I escaped it to: var re = /\\(?<=color:\\s\\)([az]+)/i which stops the Javascript error, but won't match the strings any more.

What am I doing wrong?

As an aside... can anyone point me to expanding this regex to exclude anything followed by a bracket? I am trying to get color names only, so "color: black;" should match, also "box-shadow: black... etc" should match, but ideally, not "color: rgb(... etc"

It is true that JS does not support look-behinds, although there are workarounds :

  • Reverse the string and then matches that enables using look-aheads
  • Use capturing groups
  • Use a while loop with re.lastIndex manipulation

In this case, it is much easier to use the capturing group:

 var re = /\\bcolor:\\s*([az]+)/ig; var str = ' color: black'; var m; while ((m = re.exec(str)) !== null) { if (m.index === re.lastIndex) { re.lastIndex++; } // m[1] is holding our value! document.getElementById("res").innerHTML = m[1]; } 
 <div id="res"/> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM