我使用replace
将一个字符串中的所有单词用<a/>
标签包装,但是如果一个单词包含短划线或连字符,则会将单词分开,例如:hello-there
变成hello - <a>there</a>
。JavaScript替换:不要在连字符(正则表达式)上分割单词
这是我现在使用:
string.replace(/\b(\w+)\b/g, '<a href="javascript:void(0)">$1</a>');
此外,我怎么能自言删除周期或逗号?
我使用replace
将一个字符串中的所有单词用<a/>
标签包装,但是如果一个单词包含短划线或连字符,则会将单词分开,例如:hello-there
变成hello - <a>there</a>
。JavaScript替换:不要在连字符(正则表达式)上分割单词
这是我现在使用:
string.replace(/\b(\w+)\b/g, '<a href="javascript:void(0)">$1</a>');
此外,我怎么能自言删除周期或逗号?
<script type="text/javascript">
var str="hello-there";
document.write(str.replace(/\b([\w+-]+)\b/g,'<a href="javascript:void(0)">$1</a>')
);
</script>
\w
在正则表达式中不包括破折号(-
),所以你的匹配将明确地排除你的单词包装中的那些。换句话说,由于
hello-there
您正则表达式将会看到:
word(hello) non-word(-) word(there)
试试这个:
replace(/\b([\w-])+\b/, ...)
明确包括了 “这是一个单词的一部分” 阶级划线。
注 “词语-字母” .replace(/ \ B([\ W - ] +)\ b/g的, '')//返回 “” “的话 - ” 取代(/ \ b([\ w - ] +)\ b/g,'')//返回“ - ”,因为破折号前的字符是一个字母。 – Kareem 2015-09-02 14:34:35
这个作品,谢谢! – user759235 2011-05-19 19:11:41
注意:字符类中的“+”符合文字“+”字符 - 它不是一个量词。 – eldarerathis 2011-05-19 19:12:50