Skip to content Skip to sidebar Skip to footer

Trying To Get A Regex To Recognize And Extract Words From Both CamelCase And CamelCase

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 pa

Solution 1:

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

Solution 2:

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>');

Solution 3:

The problem is that grouping with () does not store the separate groups in different array elements. Matching with (ab)(cd) will always output the same as (abcd).

Now unless the situation is more complicated than you're letting on, simply /([A-Z]*[a-z]+)/g will do.

var result = 'MyOwnVar'.match(/([A-Z]*[a-z]+)/g);
document.getElementById('one').innerHTML = result.join();

result = 'myOwnVar'.match(/([A-Z]*[a-z]+)/g);
document.getElementById('two').innerHTML = result.join();
<div id="one"></div>
<div id="two"></div>

For other situations, for instance input like HTMLContent, see the other answer(s).


Solution 4:

Try this instead:

    'MyOwnVar'.match(/([a-z]+)|([A-Z][a-z]+)/g)

    'myOwnVar'.match(/([a-z]+)|([A-Z][a-z]+)/g)

Post a Comment for "Trying To Get A Regex To Recognize And Extract Words From Both CamelCase And CamelCase"