I want to write a Javascript function to change the text Lasvegas in string: example:
"Hello every one in Lasvegas, come to <a href='xxx'>Lasvegas</a> with me"
How can I change the text "Lasveg开发者_如何学Goas" but not change the content Lasvegas that is in an HTML tag?
May be something like that
str.replace(/Lasvegas[^<]/,'123')
EDIT: Forgot JavaScript supports negative lookaheads:
"Hello every one in Lasvegas, come <a href='xxx'>Lasvegas</a> with me"
.replace(/(Lasvegas(?!<))/g, "World");
Returns:
Hello every one in World, come <a href='xxx'>Lasvegas</a> with me
Left in so everyone can see how pointless my first answer was ;-)
Alexey's answer would work if "Lasvegas" wasn't at the end of the string. I'm not sure if there's a better way, but you could use a replacer function to assert whether the text is inside a tag or not:
var str = "Hello every one in Lasvegas, come <a href='xxx'>Lasvegas</a> with me";
var out = str.replace(
/(>?Lasvegas<?)/g,
function ($0)
{
if ($0.slice(0,1) == ">")
return $0;
else
return "World";
}
);
contents of out
:
Hello every one in World, come <a href='xxx'>Lasvegas</a> with me
精彩评论