Skip to content Skip to sidebar Skip to footer

Js Regex To Find Multiple Substrings In String

I would like to find out if certain substrings exists in a string. I have tried this: x = 'AAABBBCCC' x.match(/(AAA|CCC)/) However this resurns: Array [ 'AAA', 'AAA' ] I would lik

Solution 1:

Now you have just one capture group with one value and it's returned if found.

If you add global flag to regex it returns all results

x.match(/(AAA|CCC)/g)

-> ["AAA", "CCC"]


Solution 2:

check for a global match, otherwise it will break when found the first

x = "AAABBBCCC"
x.match(/(AAA|CCC)/g)

Solution 3:

This is possible using the g global flag in your pattern. Like so:

x.match(/(AAA|CCC)/g);

This will return ["AAA", "CCC"]. I really enjoy using RegExr when figuring out expressions and as a documentation.


Solution 4:

var regEx = new RegExp('(AAA|CCC)','g');
var sample_string="AAABBBCCC";
var result = sample_string.match(regEx);
document.getElementById("demo").innerHTML = result;
<p id="demo"></p>

Post a Comment for "Js Regex To Find Multiple Substrings In String"