I’m trying to figure out how I replaces/removes parts of text in string in realtime using jQuery.
This is what i got now:
$str = 'This is a <b>test</b>. Its not going well!';
echo '<div class="element">';
echo '<span>'.$str.'</span>';
echo '</div>';
echo '<p>Remove</p>';
$('p').click(function() {
$('.element span').each(function() {
var test = array('<b>','</b>','well');
//var test = 'not';
console.log($(this).text());
var text = $(this).text().replace(test, '');
$(this).text(text);
});
});
The problem: As above nothing happens. If I use the var test = ‘not’; instead of the array part it works except it also removes the <b> tags?
How do I get the array part to work and why is it removing htmltags when executed?
If you want to use jQuery, then you need to use html() instead of text() so the bold tags are preserved.
$('p').click(function() {
$('.element span').each(function() {
var test = 'not',
text = $(this).html().replace(test, '');
$(this).html(text);
});
});
Also JS arrays are called as [] or new Array, you should have got a notice that array() is not a function in the console… and changing it to an array, you still needed to do a loop, see the above post for the example…