Javascript String Replace
I have a string of tags delimite开发者_运维知识库d 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!
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.
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);
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);
精彩评论