jQuery: Replace from string using array?

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?

Thanks in advance :wink:

You can do it easily without jQuery.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <title></title>
        <style type="text/css"></style>
        <script type="text/javascript">
            function removeTxt(){
                var test = new Array('<b>','</b>','not');
                var str = document.getElementById('mySpan').innerHTML;
                for(i=0; i < test.length; i++){
                    str = str.replace(test[i],'');
                }
                document.getElementById('mySpan').innerHTML = str;
            }
            window.onload=function(){
                document.getElementById('btnRemove').onclick = removeTxt;
            }
        </script>
    </head>
    <body>
        <?php
        $str = 'This is a  <b>test</b> . Its not going well !';
        echo '<div class="element">';
        echo '<span id="mySpan">' . $str . '</span>';
        echo '</div>';
        ?>
        <div>
            <button id="btnRemove">Remove</button>
        </div>
    </body>
</html>

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…