[英]Replace text in html string
I'm trying to write a regular expression for following criteria 我正在尝试为以下条件编写正则表达式
The source string might optionally contain an html code. 源字符串可以选择包含html代码。 Which should be preserved, everything outside tag should replace with a static text. 哪个应该保留,标签外的所有内容都应该替换为静态文本。
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) ) ;
Resultant strings must be 结果字符串必须是
//string1 must become
<span>Title</span> Hello!!!
//string2 must become
Hello!!!
You may do following: 你可以这样做:
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);
}
This, however, is probably not the best solution and will not work for nested tags but fit your examples. 但是,这可能不是最佳解决方案,不适用于嵌套标签,但适合您的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.