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 like to know exactly which substrings were present (e.g. Array [ "AAA", "CCC" ]
)
Is this possible?
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 like to know exactly which substrings were present (e.g. Array [ "AAA", "CCC" ]
)
Is this possible?
Share Improve this question asked Jul 27, 2017 at 9:07 user3715117user3715117 571 silver badge7 bronze badges4 Answers
Reset to default 7Now 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"]
check for a global match, otherwise it will break when found the first
x = "AAABBBCCC"
x.match(/(AAA|CCC)/g)
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.
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>