vinced
vinced

Reputation: 21

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 some 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!

Upvotes: 2

Views: 2309

Answers (4)

Wayne Brantley
Wayne Brantley

Reputation: 694

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>")

Upvotes: 0

moinudin
moinudin

Reputation: 138357

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.

Upvotes: 2

Chandu
Chandu

Reputation: 82903

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>

Upvotes: 0

Amber
Amber

Reputation: 526613

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>');

Upvotes: 0

Related Questions