Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete string from string with regex and jQuery/JS?

I wonder, how to delete:

<span>blablabla</span>

from:

<p>Text wanted <span>blablabla</span></p>

I'm getting the text from p using:

var text = $('p').text();

And for some reason I'd like to remove from var text the span and its content.

How can I do it?

like image 542
sunpietro Avatar asked Nov 26 '11 20:11

sunpietro


3 Answers

It's impossible to remove the <span> from the variable text, because it doesn't exist there — text is just text, without any trace of elements.

You have to remove the span earlier, while there is still some structure:

$('p').find('span').remove();

Or serialize the element using HTML (.html()) rather than plain text.

Don't edit HTML using regular expressions — HTML is not a regular language and regular expressions will fail in non-trivial cases.

var html = $('p').html();

var tmp = $('<p>').html(html);
tmp.find('span').remove();

var text = tmp.text();
like image 52
Kornel Avatar answered Nov 18 '22 18:11

Kornel


text = text.replace(/<span>.*<\/span>/g, '');
like image 32
mephisto123 Avatar answered Nov 18 '22 16:11

mephisto123


to remove the unwanted whitespace before the <span> use

text = text.replace(/\s*<span>.*<\/span>/g, '');

leaving you with

<p>Text wanted</p>
like image 1
Lloyd Avatar answered Nov 18 '22 18:11

Lloyd