Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to regex, and add "-" between words?

UPDATED

I been looking around in the old interweb to see if there is any way I can regex this as part of a replace method I'm doing: str.replace(/\w[A-Z]/gm, "-")

thisIsARegex

into this:

this-Is-A-Regex

I tried to mess around on regex101 with matching a \w character followed by [A-Z] but failed. Any thoughts?

like image 233
Tiago Ruivo Avatar asked Dec 13 '22 09:12

Tiago Ruivo


1 Answers

If the first char can't be uppercase:

var str = "thisIsARegex";
str = str.replace(/(?=[A-Z])/g, "-");
console.log(str);  // this-Is-A-Regex

If the first char can be uppercase:

var str = "ThisIsARegex";
str = str.replace(/.(?=[A-Z])/g, "$&-");
console.log(str);  // This-Is-A-Regex

or

var str = "ThisIsARegex";
str = str.replace(/\B(?=[A-Z])/g, "-");
console.log(str);  // This-Is-A-Regex

(Last snippet suggested by @Thomas.)

like image 94
ikegami Avatar answered Dec 25 '22 09:12

ikegami