簡體   English   中英

替換html字符串中的文本

[英]Replace text in html string

我正在嘗試為以下條件編寫正則表達式

源字符串可以選擇包含html代碼。 哪個應該保留,標簽外的所有內容都應該替換為靜態文本。

function replaceCode( mystring ){
    var replaceWith = "Hello!!!" ;
    //do something with mystring here..
}

var string1 = "<span>Title</span> A small note" ;
var string2 = "Another big note" ;

alert( replaceCode(string1) ) ;
alert( replaceCode(string2) ) ;

結果字符串必須是

//string1 must become
<span>Title</span> Hello!!!

//string2 must become
Hello!!!

你可以這樣做:

var yourString = "<span>Title</span> any text to replace";
var yourReplacement = "Hello!";

//Split by html tags
var tokens = yourString.split(/<\w+>\w+<\/\w+>/);

for (var i = 0; i < tokens.lenght; i++) {
   yourString = yourString.replace(tokens[i], yourReplacement);
}

但是,這可能不是最佳解決方案,不適用於嵌套標簽,但適合您的示例。

暫無
暫無

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

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