I am trying to split a string using a regex which will ideally split the string on every whitespace character, underscore, and uppercase letter.
Currently what I have is:
'hello World Goodbye' = ['hello', 'W', 'orld', 'G', 'oodbye']
['hello', 'World', 'Goodbye']
From your comment:
My intent is to be able to parse any string with underscores, whitespace, or uppercase letters and place hyphens between those "words". However strings may sometimes come in the form of
helloWorldGoodbye, which are clumped together in camel case and harder to separate.
To split on a space or an underscore, use a character class
[\s_]+. To additionally split before a capital letter, use a look-ahead.
Altogether, that would look like:
And you can use it like this:
var str = "HelloWorld good_bye"; str = str.split(/[\s_]+|(?=[A-Z])/).join("-"); document.body.innerHTML = str;
"hello World Goodbye" -> "hello-World-Goodbye" "hello_World_Goodbye" -> "hello-World-Goodbye" "helloWorldGoodbye" -> "hello-World-Goodbye"