简体   繁体   中英

regular expression for inserting something before what is matched

I want to know the regular expression for inserting characters BEFORE the matched characters from the Regular Expression. For example:

var string = "HelloYouHowAreYou"
var regEx = /[A-Z\s]/g    //to identify capital letters, but want to insert a dash before them
string = string.replace(regEx,"-")
console.log(string)

How can I accompish this?

You could use a positive lookahead, which looks for the specified characters, but not insert it into the match group and prevent the first character to get a dash at the beginning of the string.

/(?!^)(?=[A-Z])/g

 var string = "HelloYouHowAreYou", regEx = /(?!^)(?=[AZ])/g; string = string.replace(regEx, "-"); console.log(string); 

You just need to use $& backreference in the replacement pattern to refer to the whole match:

 var string = "HelloYouHowAreYou" var regEx = /[AZ\\s]/g; string = string.replace(regEx,"-$&") console.log(string) 

If you want to avoid matching the uppercase ASCII letter at the beginning of the string, add a (?!^) at the beginning:

 var string = "HelloYouHowAreYou" var regEx = /(?!^)[AZ\\s]/g; string = string.replace(regEx,"-$&") console.log(string) 

Note that \\s matches whitespace. If you want to only match uppercase ASCII letters, use

/[A-Z]/g

Wiktor Stribiżew has a great answer already, but you can also pass a function to the replace method if you want to do additional manipulation of the string.

    var string = "HelloYouHowAreYou"
    var regEx = /[A-Z\s]/g    //to identify capital letters, but want to insert a dash before them
    function replacer(match) {
      return ('-') + (match);
    }
    string = string.replace(regEx,replacer)
    console.log(string)

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