I'm trying to write a regular expression for following criteria
The source string might optionally contain an html code. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.