开发者

jquery - Remove a dynamic word in a text

开发者 https://www.devze.com 2023-03-19 01:03 出处:网络
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开发者_StackOverflow=\"list\"

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开发者_StackOverflow="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.


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


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


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);
    });
});
0

精彩评论

暂无评论...
验证码 换一张
取 消