selecting text between round brackets in javascript
I need to select a text using javascript that is between round brackets, and wrap it all in a span:
<p>Just some text (with some text between brackets) and some more text</p>
should become:
<p>Just some text <span class="some-class">(with some text between brackets)</span> and so开发者_如何学编程me more text</p>
I think something like this should be possible using regex, but i'm totally unfamiliar with using regex in javascript. Can someone please help? Thanks!
This should do the trick (str
is the string holding the text you want to manipulate):
str.replace((\([^()<>]*\)), "<span class=\"some-class\">$1</span>");
It disallows (
, )
, <
or >
within the parenthesis. This avoids nesting issues and html tags falling in the middle of the parenthesis. You might need to adapt it to meet your exact requirements.
Since you're new to regular expressions, I recommend reading http://www.regular-expressions.info/ if you want to learn more.
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>');
Try this:
<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>
Using RegExp object:
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>" );
Using literal:
var myArray = str.replace(/\(+(.*)\)+/g,"<span class="some-class">($1)</span>")
精彩评论