2

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?

4 Answers 4

7

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"]

Sign up to request clarification or add additional context in comments.

Comments

2

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

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

Comments

0

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.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.