jQuery:包装一个匹配正则表达式的字符串

时间:2021-08-19 04:57:11

In a certain element, I need to select different strings that match a certain regex and wrap them with tags. How can I do that ?

在某个元素中,我需要选择与某个正则表达式匹配的不同字符串并用标签包装它们。我怎样才能做到这一点 ?

I tried :

我试过了 :

var str = jQuery("#my_div").html();
var regex = "\([a-z]{2}\)";
jQuery("#my_div").html(str.replace(regex, "<span>$1</span>"));

.. but this wraps the whole element instead of the selected string in the element.

..但是这会包裹整个元素而不是元素中的选定字符串。

2 个解决方案

#1


5  

The problem with your example is you have no capturing group, change your regex to (\([a-z]{2}\))

您的示例的问题是您没有捕获组,将正则表达式更改为(\([a-z] {2} \))

Here is an example of a working regex replace in html: http://jsfiddle.net/gibble/NYVWg/

以下是html中正则表达式替换的示例:http://jsfiddle.net/gibble/NYVWg/

<style>span.highlight { color: purple; }​</style>
<body>bla bla <div id="test">this (is) some text this (is) some text</div> bla bla​<body>

var oldHtml = $('#test').html();
var newHtml = oldHtml.replace(/(\([a-z]{2}\))/g,"<span class='highlight'>$1</span>");
$('#test').html(newHtml);​

#2


2  

Your code should work given that your regex has a subexpression in it. Check out this jsfiddle:

鉴于您的正则表达式中包含子表达式,您的代码应该可以正常工作。看看这个jsfiddle:

HTML:

HTML:

​<div id="my_div">foo bar my_regex foo bar</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

JS:

JS:

var str = jQuery("#my_div").html();
var regex = /(my_regex)/;
jQuery("#my_div").html(str.replace(regex, '<span class="red">$1</span>'));​​​​​​​​​

CSS:

CSS:

​.red {
    color : red;
}​

#1


5  

The problem with your example is you have no capturing group, change your regex to (\([a-z]{2}\))

您的示例的问题是您没有捕获组,将正则表达式更改为(\([a-z] {2} \))

Here is an example of a working regex replace in html: http://jsfiddle.net/gibble/NYVWg/

以下是html中正则表达式替换的示例:http://jsfiddle.net/gibble/NYVWg/

<style>span.highlight { color: purple; }​</style>
<body>bla bla <div id="test">this (is) some text this (is) some text</div> bla bla​<body>

var oldHtml = $('#test').html();
var newHtml = oldHtml.replace(/(\([a-z]{2}\))/g,"<span class='highlight'>$1</span>");
$('#test').html(newHtml);​

#2


2  

Your code should work given that your regex has a subexpression in it. Check out this jsfiddle:

鉴于您的正则表达式中包含子表达式,您的代码应该可以正常工作。看看这个jsfiddle:

HTML:

HTML:

​<div id="my_div">foo bar my_regex foo bar</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

JS:

JS:

var str = jQuery("#my_div").html();
var regex = /(my_regex)/;
jQuery("#my_div").html(str.replace(regex, '<span class="red">$1</span>'));​​​​​​​​​

CSS:

CSS:

​.red {
    color : red;
}​