I have the following text as an input.
This is specified input. This is Specified input.
And I want the below output.
This is <span>specified</span> input. This is <span>Specified</span> input.
If I do str.replace(\\specified\\gi, '<span>specified</span>')
it will replace like this
This is <span>specified</span> input. This is <span>specified</span> input.
How can I replace this string with the matched element
Replace with <span>$&<span>
to insert the matched text:
const str = 'This is specified input. This is Specified input.'; const result = str.replace(/specified/gi, '<span>$&<span>'); console.log(result);
Use $&
to retrieve the matched string.
You also have the wrong kind of slash around your regexp.
var str = "This is specified input. This is Specified input."; console.log(str.replace(/specified/gi, '<span>$&</span>'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.