简体   繁体   中英

Remove text bricks that are defined in an array from input value

I want to edit the value of an input field! To detail i want to delete the text that that is defined an an array from the input: So if i have for example:

<input value="hello what is your">

and this array:

var arr = ["hello","is"];

I want to change the value of the input to:

<input value="what your">

How should i start? Thanks http://jsfiddle.net/rRXAG/

How should i start?

1) Iteration - Since you already use jQuery, try with $.each .
2) string.indexOf() - returns -1 if it is not present

var arr = ["hello","is"];
$.each(arr, function (i, j) {
    var inTxt = $('input').val();
         if (inTxt.indexOf(j) != -1) {
               $('input').val(inTxt.replace(j, ''));
}
});});

JSFiddle

Assuming the values are words separated by spaces, you can do this:

1) Store the values into a map

var map = {};
for (var i in arr) map[arr[i]] = true;

2) Get the value from your input (it's a string) and filter it

var inputVal = $('input').first().val();
var newValue = inputVal.split(" ").filter(function(x) { 
  return !map[x]; 
}).join(" ");

// Set new value
$('input').first().val(newValue);
var val=document.getElementById("yourid").value;
for(var i=0;i<arr.length;i++){
    val.replace(arr[i],"")
}
document.getElementById("yourid").value=val;

This regexp do the job :

$('input').first().val().replace(new RegExp(arr.join('|'), 'g'), '');

Fiddle : http://jsfiddle.net/rRXAG/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM