我使用 replace
用 <a/>
将所有单词包装在一个字符串中标签,但如果单词包含破折号或连字符,它将拆分单词,例如:hello-there
变成 hello - <a>there</a>
.
这是我现在使用的:
string.replace(/\b(\w+)\b/g, '<a href="javascript:void(0)">$1</a>');
另外,如何从单词中删除句点或逗号?
最佳答案
正则表达式中的
\w
不包含破折号 (-
),因此您的匹配项会明确地将这些破折号从您的文字换行中排除。换句话说,给定
hello-there
您的正则表达式将看到:
word(hello) non-word(-) word(there)
试试这个:
replace(/\b([\w-])+\b/, ...)
在“这是单词的一部分”类中明确包含破折号。
关于Javascript 替换 : don't split word on hyphen (regular expressions),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6063571/