Reputation: 35
I'm trying to use react-string-replace to match all $Symbols within a string of text.
Here are a few example values we'd like to be matched (stock / crypto / forex pairs): $GPRO, $AMBA, $BTC/USD, $LTC/ETH
Here is our attempted regex
/\$\S+[^\s]*/g
when passing the string
$this works great $this/works great too.
through .match()
- the proper symbols are returned in an array.
0: "$this"
1: "$this/works"
When using
reactStringReplace() - each match is returning
works great
Any ideas why
reactStringReplace()
seems to be handling this regex incorrectly?
Thanks ya'll!
Upvotes: 1
Views: 312
Reputation: 626728
Check the React String Replace
documentation, it is written there:
reactStringReplace(string, match, func)
...
match
Type:regexp|string
The string or RegExp you would like to replace withinstring
. Note that when using aRegExp
you MUST include a matching group.
Why should you add a capturing group? See the replaceString
function. There is var result = str.split(re);
line that uses the pattern to actually split the contents you pass to the regex with your pattern thus tokenizing the whole input into parts that match and those that do not match your regex.
If you do not add a group to the regex passed as a String, the capturing parentheses will be added automatically around the whole pattern:
if (!isRegExp(re)) {
re = new RegExp('(' + escapeRegExp(re) + ')', 'gi');
}
If you pass your regex as a RegExp without capturing parentheses, the matches will be missing from the resulting array, hence, they will disappear.
So, use
/(\$\S+)/g
If you want to keep the $
chars in the output, or
/\$(\S+)/g
if you want to omit the dollars.
Upvotes: 1