javascript文本中的模式匹配

时间:2013-02-26 17:06:51

标签: javascript regex

我的文字里面有%text%的图案。 如何在javascript中获取这些模式以将其包装在跨度和更改颜色中?

谢谢!

3 个答案:

答案 0 :(得分:2)

var str = 'Some text with patterns like %text% inside.';

str = str.replace( /%([^%]+)%/g, '<span style="color: blue">$1</span>' );    
// Some text with patterns like <span style="color: blue">text</span> inside.

答案 1 :(得分:0)

使用Regex

if (String.match(/text/gi)) {
    //wrap span around String and change color of CSS
}

答案 2 :(得分:0)

如果%之间的模式始终是纯文本(不包括空格等),则可以执行以下操作:

text = text.replace(/%\w*%/g, function (txt) {
    return '<span style="color: red">' + txt.substring(1, txt.length-1) + '</span>';
});

虽然MikeM的匹配模式远远领先于我,但我将这个答案留给show,你如何使用一个函数来操作匹配的字符串,甚至完成其他一些事情,具体取决于匹配。

相关问题