[英]javascript split string selected text remove
How do I delete a fragmented of text from within a string with javascript如何使用javascript从字符串中删除碎片化的文本
Example String:示例字符串:
var start = "World,Book,Pencil,Door";
Now, when I select any of the selected values: "World"
, I want the result to be "Book,Pencil,Door"
.现在,当我选择任何选定的值时:
"World"
,我希望结果是"Book,Pencil,Door"
。
// result = "Book,Pencil,Door";
If you are asking how to remove a value from a comma separated string, try this ...如果您询问如何从逗号分隔的字符串中删除值,请尝试以下操作...
var removeValue = function(list, value, separator) {
separator = separator || ",";
var values = list.split(separator);
for(var i=0; i<values.length; i++) {
if(values[i]===value) {
values.splice(i, 1);
return values.join(separator);
}
}
return list;
}
If the value you're looking for is found, it's removed, and a new comma delimited list returned.如果找到了您要查找的值,则会将其删除,并返回一个新的逗号分隔列表。 If it is not found, the old list is returned.
如果未找到,则返回旧列表。
Another version ... using indexOf另一个版本......使用 indexOf
var removeValue = function(list, value, separator) {
separator = separator || ",";
var values = list.split(separator);
var index = values.indexOf(value);
if(index >= 0) {
values.splice(index, 1);
return values.join(separator);
} else {
return list;
}
}
Basically, with either function you send the list ( "World,Book,Pencil,Door"
) as a string, the value to remove ( "World"
) as another string and what the separator is ( ","
for comma ... however, comma is also the default so can be left off).基本上,使用任何一个函数,您都可以将列表 (
"World,Book,Pencil,Door"
) 作为字符串发送,将要删除的值 ( "World"
) 作为另一个字符串发送,以及分隔符是什么 ( ","
表示逗号...但是,逗号也是默认值,因此可以省略)。 If the value to remove does not exist in the list, it will return the list.如果列表中不存在要删除的值,它将返回列表。 If it is in the list, it will be removed.
如果它在列表中,它将被删除。
Example 1 :示例 1 :
var final = removeValue("World,Book,Pencil,Door", "World");
// final = "Book,Pencil,Door"
Example 2 :示例 2 :
var final = removeValue("World,Book,Pencil,Door", "House");
// final = "World,Book,Pencil,Door"
Example 3 :示例 3 :
var final = removeValue("World|Book|Pencil|Door", "World", "|");
// final = "Book,Pencil,Door"
UPDATE :更新:
jsFiddle: http://jsfiddle.net/rfornal/96awa2ht/ jsFiddle: http : //jsfiddle.net/rfornal/96awa2ht/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.