views:

176

answers:

1

I have a requirement to place text between brackets using jQuery; the content will be updated once an action occurs e.g. search.

The structure is: -

<h2>Placeholder Text Placeholder Text Placeholder Text ()</h2>
+2  A: 

You can use the indexOf method:

text = $("h2").text();
pos1 = text.indexOf("(");
pos2 = text.indexOf(")");
newText = text.substring(0, pos1 + 1) + myText + text.substring(pos2);

The above assumes that one and only one pair of brackets is to be found in the text.

kgiannakakis
Thanks but this won't work as it will continually prefix the new count before the old count, I need it to replace the content of () with the new count number. I should mention that the state of the string could contain numbers already; at variable length.
See my edited answer.
kgiannakakis
What if the closing bracket is before the opening bracket?
Gumbo
kgiannakakis