I create the regex /(10?|10{2,})/g to find 1,10 or 100,1000… but the code below doesn’t return the expected result. I don’t know where I went wrong, please help me!
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p>Do a global search for a "1", followed by zero or one "0" characters:</p>
<p id="demo"></p>
<script>
let text = "1, 10, 100 or 1000?";
let result = text.match(/(10?|10{2,})/g);
//should return 1,10,100,1000 but instead return 1,10,10,10
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
2
Answers
Your issue is that
10?
will match all the1
,10
,100
,1000
in your string, and since that is the first element in the alternation, the regex engine stops when it matches (and so your longest match is10
). You could solve that by swapping the alternation around so that the longest match is first:But better yet, just simplify the regex to
10*
(1
followed by 0 or more0
s):Note also that you don’t need a capturing group
(...)
in your regex as you are only interested in the whole match.I will add.
Search substrings:
Output:
Search words only on pattern:
Output:
Search words only on pattern 1 and more zeroes:
Output:
Find words ending in a pattern of 1 or more zeros:
Output:
Finds words ending only in a pattern of 1 or more zeros:
Output: