1

When I user click on the button remove word and as enter 2 in the input box it should remove it from the element id="list"

<input type="text" id="word"><input type="button" value="remove word">

<span id="list">1,2,3</span>

I did the following on the click event:

var text = $('.word').val();
    $('#list').html($('#list').html().replace(/text/ig, ""));

I understand it looks for the string text and not the var. So how can I change the syntax to make it search for the var.

Yannick
  • 3,553
  • 9
  • 43
  • 60

3 Answers3

2
var text = $('.word').val();
    $('#list').html($('#list').html().replace(new Regexp(text, "ig"), ""));
Dogbert
  • 212,659
  • 41
  • 396
  • 397
  • 1
    Please note though that JavaScript is case-sensitive. – pimvdb Jul 10 '11 at 19:20
  • Yes thanks...works great...Also sorry if I didn't explain properly but when I remove a item from the list the comma will still be there so I'm looking for a function to remove the item from the list comma included? – Yannick Jul 10 '11 at 20:20
  • @Yannick: I added your extra need in my answer. – pimvdb Jul 10 '11 at 21:10
2

Literal regexps (/.../) are literal in such a way that they cannot contain variables. You'd need to construct a regexp this way:

var text = $('.word').val();
$('#list').html($('#list').html().replace(new RegExp(text, "ig"), ""));

Edit: If you need to have following commas removed, you'd be best off by parsing it as an Array and removing the appropriate element:

var text = $('.word').val();
var array = $('#list').html().split(","); // split into an Array
                                          // items are delimited by a comma
while(array.indexOf(text) > -1) {         // as long as text is in the array...
    array.splice(array.indexOf(text), 1); // remove one element from the array
                                          // at the position the text is
}
$('#list').html(array.join(","));         // concatenate the elements with a
                                          // comma again
pimvdb
  • 151,816
  • 78
  • 307
  • 352
1

You may use this code, here's the jsfiddle: http://jsfiddle.net/gk5pV/ . Documentation is inline:

jQuery(document).ready(function($) {
    $("#replaceButton").click(function() {
        // find the word
        var text = $('#word').val();

        // create a regex
        var re = new RegExp(text, "gi");

        // replace the inner html
        // please note: this may cause serious problems when not used on textnodes
        // see: http://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery
        var replacedHTML = $('#list').html().replace(re, "");

        // replace
        $('#list').html(replacedHTML);
    });
});
Arend
  • 3,741
  • 2
  • 27
  • 37