我需要使用圆括号之间的javascript选择一个文本,并将其全部包含在一个范围内:
<p>Just some text (with some text between brackets) and some more text</p>
应该成为:
<p>Just some text <span class="some-class">(with some text between brackets)</span> and some more text</p>
我认为使用正则表达式应该可以做到这一点,但我完全不熟悉在javascript中使用正则表达式。有人可以帮忙吗?谢谢!
答案 0 :(得分:2)
这应该可以解决问题(str
是包含您想要操作的文本的字符串):
str.replace((\([^()<>]*\)), "<span class=\"some-class\">$1</span>");
它不允许括号内的(
,)
,<
或>
。这样可以避免嵌套问题和html标记落在括号中间。您可能需要对其进行调整以满足您的确切要求。
由于您不熟悉正则表达式,如果您想了解更多信息,我建议您阅读http://www.regular-expressions.info/。
答案 1 :(得分:0)
oldString = '<p>Just some text (with some text between brackets) and some more text</p>';
newString = oldString.replace(/\((.*?)\)/g, '<span class="some-class">($1)</span>');
答案 2 :(得分:0)
试试这个:
<p id="para">Just some text (with some text between brackets) and some more text</p>
<input type="button" value="Change Text" onclick="ChangeText()"/>
<script>
function ChangeText()
{
var para = document.getElementById("para");
var text = para.innerHTML;
para.innerHTML = text.replace(/(.*)(\(.*\))(.*)/g, "$1<span class=\"some-class\">$2</span>$3")
}
</script>
答案 3 :(得分:0)
使用RegExp对象:
var str = "<p>Just some text (with some text between brackets) and some more text</p>";
var re = new RegExp("\(+(.*)\)+", "g");
var myArray = str.replace(re,"<span class="some-class">($1)</span>" );
使用文字:
var myArray = str.replace(/\(+(.*)\)+/g,"<span class="some-class">($1)</span>")