How do you use the matched variables in the pattern in the replacement string?
var regexp = new RegExp('needle', 'ig');
str.replace(regexp, '<span class="marked">//1</span>')
replace() The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.
The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.
To use variable in string match with JavaScript, we can use the RegExp constructor to create our regex. const re = new RegExp(vowels, "gi"); The first argument is the regex pattern string and the 2nd argument is the string with the flags. g means we return all matches and i means we search in a case-insensitive manner.
JavaScript match() Function. The string. match() is an inbuilt function in JavaScript used to search a string for a match against any regular expression. If the match is found, then this will return the match as an array.
try
var regexp = new RegExp(something, 'ig');
str.replace(regexp, '<span class="marked">$&</span>')
References:
A table specifying the format of different tokens to be used into the replacement string
An example on how to switch two words into a string
The correct way to use backreferences in JavaScript is via $1
...$9
.
To make your example work:
var regexp = new RegExp(something, 'ig');
var result = str.replace(regexp, '<span class="marked">$1</span>');
More information is available here: http://www.regular-expressions.info/javascript.html#replace
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