Javascript Regex: how to simulate "match without capture" behavior of positive lookbehind? -
i have relatively simple regex problem - need match specific words in string, if entire words or prefix. word boundaries, this:
\b(word1|word2|prefix1|prefix2)
however, can't use word boundary condition because words may start odd characters, e.g. .999
my solution whitespace or starting token these odd cases.
(\b|^|\s)(word1|word2|prefix1|prefix2)
now words .999 still matched correctly, captures whitespace preceding matched words/prefixes. purposes, can't have capture whitespace.
positive lookbehinds seem solve this, javascript doesn't support them. there other way can same behavior solve problem?
you can use non-capturing group using (?:)
:
/(?:\b|^|\s)(word1|word2|prefix1|prefix2)/
update:
based on want replace (and @alanmoore's point \b
), want go this:
var regex = /(^|\s)(word1|word2|prefix1|prefix2)/g; mystring.replace(regex,"$1<span>$2</span>");
note changed first group capturing 1 since it'll part of match want keep in replacement string (right?). added g
modifier happens occurrences in string (assuming thats wanted).
Comments
Post a Comment