I have a string with comma separated values:
var x = '1,2,10,11,12';
I need to remove the value that's in y.
x = remove(x,y);
Q: Is there a function for that already or do I need to convert it to an array, remove y and then convert it back to a string?
5 Answers 5
You can do x.replace(y, ""). For more information, see the Mozilla docs.
5 Comments
Do you mean like this?
var arr = "1,2,1,2,3".split(",");
var arr2 = [];
for(var i = 0; i < arr.length; i++) {
if(arr[i] != "1") arr2.push(arr[i])
}
arr2.join(","); // "2,2,3"
4 Comments
Assuming your removing 'y' where y is an index, do this:
x = x.split(',').splice(y,1).join(',');
Edit:
In that case, I would use regex. If you wish to avoid regex, another solution is available:
while(x.indexOf(y) >= 0){
x.replace(y+',', '');
}
EDIT: Added a trailing comma to the replace, such that the list remains a comma delimited list.
1 Comment
str_replace analogon from phpjs.org:
http://phpjs.org/functions/str_replace:527
So you could use something like x=str_replace(y, '', x); ;) Or implement it yourself by using regexp!
Edit: Okay I think I got it wrong. Probably Greg's answer is the right one :-)
2 Comments
There are three things to check for
- y at the beginning of the string and followed by a comma
- y preceeded by a word break and followed by a comma
y at the end of the string and preceeded by a comma
x.replace(new RegExp('((^|\\b)' + y + ',|,' + y +'$)'),'');