I've got this halfway working. This works great:
'MyOwnVar'.match(/([a-z]*)([A-Z][a-z]+)/g)
Result:
["My", "Own", "Var"]
The goal is to pull out the individual words. But if I pass a camelCase name to it:
'myOwnVar'.match(/([a-z]*)([A-Z][a-z]+)/g)
I get:
["myOwn", "Var"]
I can't figure out what I'm doing wrong. As far as I can tell, two sets of ()
should store the matching results in two separate array elements. It's lumping them in together for some reason.
If I have understood the question properly the following regex should do the trick:
/([A-Za-z][a-z]+)/g
In case that a single character (as "m" in "mOwnVariable") should be considered as a word:
/([A-Za-z][a-z]*)/g
You can use
/([A-Z]?[a-z]+)/g
See regex explanation https://regex101.com/r/zS8vJ3/1
// For camelCase
var matches = 'myOwnVar'.match(/([A-Z]?[a-z]+)/g);
document.write('// For camelCase<pre>' + JSON.stringify(matches, 0, 2) + '</pre>');
// For CamelCase
var matches = 'MyOwnVar'.match(/([A-Z]?[a-z]+)/g);
document.write('<hr /> // For CamelCase <pre>' + JSON.stringify(matches, 0, 2) + '</pre>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With