【发布时间】:2014-05-04 23:34:18
【问题描述】:
假设我有一个 HTML 字符串
var _str = <div>The European languages are members of the same family. <div class="same">Their separate existence is a myth.</div> For science, music, sport, etc, Europe uses the same vocabulary. The languages only differ in their grammar, <div class="same">their pronunciation and their most common words.</div></div>
我想把文字same替换成<span class="highlighted">same</span>
我在做_str.replace('same', '<span class="highlighted">same</span>'); 所以它也将class="same" 替换为class="<span class="highlighted">same</span>"
谁能帮助我如何只替换节点( )内的文本而不是任何内容?
【问题讨论】:
-
你不能在替换和跨度上的“相同”的任一侧添加一个空格吗?
_str.replace(' same ', '<span class="highlighted"> same </span>'); -
@JamieBarker 如果单词后面跟着标点符号怎么办?
"we are the same." -
只需在 'same' 前留一个空格 _str.replace('same', ' same');
-
真的,这是针对 HTML 使用正则表达式的问题。您应该将
_str解析为 HTML 结构,然后在每个单独的节点处替换单词same -
@RGraham 我想这样做,但我怎么知道我要替换的字符串不在任何 HTML 标记中,即。
<same>.
标签: javascript jquery html string replace