So I want to capture the sub-string between two special characters in JavaScript, using regular expressions.
Say I have the string "$Hello$, my name is $John$"
, I would want .match to return the array of [Hello, John]
.
*In addition, I do not want to capture the match between two matches. So I wouldn't want to capture $, my name is $, since it is technically between two '$'s.
The regular expression I have used is
var test = str.match(/(?<=\$)(.*)(?=\$)/);
Which works, but duplicates each entry twice. So it has
[Hello, Hello, John, John].
I have also used var test = str.match(/(?<=\$)[^\$]+?(?=\$)/g)
But this returns everything inbetween each match (the example i listed above $, my name is $.)
How can I fix this?
You could match the first and the second dollar sign and use a capturing group to capture char is in between using a negated character class matching any char except a dollar sign.
\$([^$]+)\$
Regex demo
Instead of using match, you could use exec. For example:
var str = "$Hello$, my name is $John$";
var regex = /\$([^$]+)\$/g;
var m;
var test = [];
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
test.push(m[1]);
}
console.log(test);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With