jQuery:包装与正则表达式匹配的字符串 [英] jQuery : wrapping a string that matches a regex

查看:112
本文介绍了jQuery:包装与正则表达式匹配的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某个元素中,我需要选择与某个正则表达式匹配的不同字符串,并用标签将它们包装起来.我该怎么办?

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 ?

我尝试过:

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.

推荐答案

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

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

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

Here is an example of a working regex replace in 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);​

这篇关于jQuery:包装与正则表达式匹配的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆