Devin Olsen
Devin Olsen

Reputation: 862

Javascript split string by first instance of lowercase character

I would like to take Pascal string inputs and split them up by hyphens.

"HelloWorld" becomes "hello-world"

I'm able to do that no problem, however my regex attempts start to break down when say a person supplies the following:

"FAQ" becomes "f-a-q"

I want it to keep FAQ as "faq", so I think I need to be splitting the string up by all first instances of a lowercase vs uppercase correct?

My regex right now is:

name.split(/(?=[A-Z])/).join('-').toLowerCase()

Upvotes: 1

Views: 274

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

You could replace the middle starting uppercase letters.

function hyphenate(string) {
    return string.replace(/[^A-Z](?=[A-Z])/g, '$&-').toLowerCase();
}

console.log(hyphenate("FAQ"));        // faq
console.log(hyphenate("ReadTheFAQ")); // read-the-faq
console.log(hyphenate("HelloWorld")); // hello-world

Upvotes: 2

Related Questions