正则表达式用HTML标签替换字符

时间:2012-03-28 22:26:47

标签: javascript html regex

我有这个示例字符串,我希望在JavaScript中使用正则表达式替换明星的开启和关闭强标记:

To increase search results, use the 8** prefix.
877 and 866 will result in more matches than 800 and 888 prefixes.
*Note*: The pattern for a custom number can be more than 7 digits. For example: 1-800-Mat-tres(s)

理想的输出是:

To increase search results, use the 8** prefix.
877 and 866 will result in more matches than 800 and 888 prefixes.
<strong>Note</strong>: The pattern for a custom number can be more than 7 digits. For example: 1-800-Mat-tres(s)

唯一需要注意的是,如果连续两个开头(如8 **),则不会被强标签取代。

提前感谢您的任何帮助。

2 个答案:

答案 0 :(得分:3)

也许你可以试试这样的东西?

\*(\S[^\*]+\S)\*

+表示1个或更多,因此只有在*之间存在某些内容时才会匹配。

[^\*]表示任何不是明星的*

<强>更新 我已经更新了上面的正则表达式,指定它与*和每个匹配的第一个和最后一个字符之间的非白色空格字符不匹配。这可以防止下面突出显示的位与错误匹配:

8 * * prefix. 877 and 866 will result in more matches than 800 and 888 prefixes. *注*

这是带注释的相同正则表达式(在javascript中)

"\\*" +       // Match the character “*” literally
"\\S" +       // Match a single character that is a “non-whitespace character”
"[^\\*]" +    // Match any character that is NOT a * character
   "+" +        // Between one and unlimited times, as many times as possible, giving back as needed (greedy)
"\\S" +       // Match a single character that is a “non-whitespace character”
"\\*"         // Match the character “*” literally

最后,这是您可以使用的javascript示例:

yourStringData.replace(/\*(\S[^\*]+\S)\*/g, "<strong>$1</strong>");

只需将yourStringData替换为包含要运行替换的数据的变量。

答案 1 :(得分:3)

如果*之间总是有

your_string.replace(/\*(\w+)\*/g, "<strong>$1</strong>");