简体   繁体   English

从输入值中删除数组中定义的文本块

[英]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/ 谢谢http://jsfiddle.net/rRXAG/

How should i start? 我应该如何开始?

1) Iteration - Since you already use jQuery, try with $.each . 1)迭代-由于您已经使用jQuery,请尝试使用$.each
2) string.indexOf() - returns -1 if it is not present 2) string.indexOf() -如果不存在则返回-1

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

JSFiddle 的jsfiddle

Assuming the values are words separated by spaces, you can do this: 假设值是用空格分隔的单词,则可以执行以下操作:

1) Store the values into a map 1)将值存储到地图中

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 2)从输入中获取值(它是一个字符串)并过滤它

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/ 小提琴: http : //jsfiddle.net/rRXAG/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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