簡體   English   中英

用 html 標簽替換一些 substring

[英]Replace some substring with html tags

嗨,我有一個字符串,如圖所示:

var testStr = 'Soft is a texture, I am soft spoken and I like softy ice cream';

想要在單詞“soft”周圍添加“span”標簽:所以結果可能是:

<span class='add-some-style'>Soft</span> is a texture, I am <span class='add-some-style'>soft</span> spoken and I like <span class='add-some-style'>soft</span>y ice cream

嘗試了 string.replace,但沒有成功。

您可以使用正則表達式來替換。 在忽略大小寫的情況下進行全局搜索。 用額外的標簽替換匹配的模式。

 var testStr = 'Soft is a texture, I am soft spoken and I like softy ice cream'; var strVariable = 'soft' var regexValue = new RegExp( `(${strVariable})`, 'ig'); const newStr = testStr.replace(regexValue, "<span class='add-some-style'>$1</span>"); console.log(newStr);

您可以使用正則表達式和字符串替換

 var testStr = 'Soft is a texture, I am soft spoken and I like softy ice cream'; const newStr = testStr.replace(/^Soft/gi, '<span class="highlight">Soft</span>'); document.getElementById('test').innerHTML = newStr;
 .highlight { color: green; }
 <div id='test'></div>

您可以在每次找到軟關鍵字時對 html 進行切片,然后使用連接來獲得結果

 var testStr = 'Soft is a texture, I am soft spoken and I like softy ice cream'; let index = 0; let acc = ''; const wordLength = 4; while (index >= 0) { const softWord = testStr.substr(index, wordLength); const preText = testStr.substring(0, index); acc += preText + '<span class="add-some-style:>' + softWord + '</span>'; testStr = testStr.substring(index + wordLength); index = testStr.toLowerCase().indexOf('soft') } console.log(acc + testStr)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM