delled delled - 16 days ago 7
jQuery Question

jquery - find the character in the string and wrap the remaining character

I have a heading like:

foobar|foo


How do I search for the character '|', then wrap it in span along with the remaining character in the right?

The result should be:

foobar< span>|foo< /span>.


In the website we have different length headings like:

hello|my mario
you are the best|my friend


So i want to detect the '|' character and wrap it with the remaining.

Answer

inspired by @guedes answer

try this:

var headingText = $('h2').text();
var newText = ( headingText.replace(/\|[^]*$/, ' <span>$&</span>') );
$('h2.heading').html(newText)


html
<h2 class="heading">foobar|foo</h2>

you can have any heading you like.e.g

bar|foo

doodle|lorem.