Mozar Mozar - 2 months ago 8
Javascript Question

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?

Answer

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

var string = "HelloYouHowAreYou"
var regEx = /[A-Z\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 = /(?!^)[A-Z\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
Comments