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?
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();
text = text.replace(/<span>.*<\/span>/g, '');
to remove the unwanted whitespace before the <span>
use
text = text.replace(/\s*<span>.*<\/span>/g, '');
leaving you with
<p>Text wanted</p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With