I have a string of tags delimited by semicolons:
"red; yellow; blue; green; purple"
I would like to strip out all the tags that do not match a substring (case-insensitive.)
For example, if I have a substring "Bl" I would like to return "blue".
Any suggestions as how to best accomplish this in javascript? Specifically, I'm wondering if there is a one-step method for doing this in regex...
Thanks in advance!
-
What should the return type be? A semicolon delimited string or an array?Mark Byers– Mark Byers2010年02月06日 23:26:40 +00:00Commented Feb 6, 2010 at 23:26
-
Sorry, I should have specified. Another semi-colon delimited string, thanks.Travis– Travis2010年02月06日 23:27:37 +00:00Commented Feb 6, 2010 at 23:27
3 Answers 3
First parse the string to an array using split(), after that iterate over the array and look for matches using match or indexOf on the items in the array. If you want to check case-insensitive you can either use a case insensitive regexp in match, or do toLowerCase on all elements being compared.
2 Comments
You can use something like this:
var needle = 'blu';
var s = 'red; yellow; blue; geen; purple';
var a = s.split('; ');
var newArray = new Array();
for (var i = 0; i < a.length; i++) {
if (a[i].indexOf(needle) != -1) {
newArray.push(a[i]);
}
}
var result = newArray.join('; ');
alert(result);
The method is basically as Simon described, with one extra step - a join at the end to convert the result back to a string.
Just for fun, here's a crazy regex based solution. Warning: if your search term contans special characters they will need to be escaped. I'm assuming that the search term will contain only non-special characters:
var s = 'red; yellow; blue; geen; purple';
var result = ('; ' + s).replace(/;(?![^;]*blu)[^;]*(?=;|$)/g, '').substring(2);
alert(result);
3 Comments
(^|\b)\w*blu\w*(; |$)function find_substring(tags, search){
var tags_array = tags.split(";");
var found_tags = [];
for(var i=0; i<tags_array.length; i++){
if(tags_array[i].indexOf(search) > -1){
found_tags.push(tags_array[i]);
}
}
if(found_tags.length > 0){
return found_tags.join("; ");
}else{
return false;
}
}
var tags = "red; yellow; blue; geen; purple";
var search = "blue";
find_substring(tags,search);