我正在尝试为以下条件编写正则表达式
源字符串可以选择包含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!!!
答案 0 :(得分:0)
您可以执行以下操作:
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);
}
然而,这可能不是最佳解决方案,不适用于嵌套标签,但适用于您的示例。