[英]How to find and replace text using regex?
我有以下文本作為輸入。
This is specified input. This is Specified input.
我想要以下輸出。
This is <span>specified</span> input. This is <span>Specified</span> input.
如果我做str.replace(\\specified\\gi, '<span>specified</span>')
它會像這樣替換
This is <span>specified</span> input. This is <span>specified</span> input.
如何用匹配的元素替換此字符串
替換為<span>$&<span>
以插入匹配的文本:
const str = 'This is specified input. This is Specified input.'; const result = str.replace(/specified/gi, '<span>$&<span>'); console.log(result);
使用$&
檢索匹配的字符串。
您的正則表達式周圍也有錯誤的斜線。
var str = "This is specified input. This is Specified input."; console.log(str.replace(/specified/gi, '<span>$&</span>'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.