简体   繁体   English

Javascript:如何替换字符串的内容,而不替换HTML标记中的内容?

[英]Javascript: How can I replace the contents of a string but not in an HTML tag?

I want to write a Javascript function to change the text Lasvegas in string: example: 我想编写一个Javascript函数来更改字符串中的文本Lasvegas :示例:

" Hello every one in Lasvegas, come to <a href='xxx'>Lasvegas</a> with me " “大家好,拉斯韦加斯,和我一起去<a href='xxx'>拉斯韦加斯</a>

How can I change the text "Lasvegas" but not change the content Lasvegas that is in an HTML tag? 如何更改文本“ Lasvegas”,而不更改HTML标记中的内容Lasvegas

可能是这样的

str.replace(/Lasvegas[^<]/,'123')

EDIT: Forgot JavaScript supports negative lookaheads: 编辑:忘记JavaScript支持否定的先行:

"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 世界上的每个人你好,<a href='xxx'>拉斯维加斯</a>


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. 如果“ Lasvegas”不在字符串末尾,则Alexey的答案将起作用。 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: 我不确定是否有更好的方法,但是您可以使用replacer函数来断言文本是否在标记内:

 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 : out内容:

Hello every one in World, come <a href='xxx'>Lasvegas</a> with me 世界上的每个人你好,<a href='xxx'>拉斯维加斯</a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM