views:

73

answers:

3

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!

+2  A: 

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.

Simon Groenewolt
Thanks Simon. I'm doing something similar to that now. I guess I was hoping there might be a one-step magical way to do it in regex. :)
Travis
+1 because this basically describes what I just implemented.
Mark Byers
@travis: If you really want a crazy regex one-liner, see my answer - I've added a method that uses regex. ;-)
Mark Byers
A: 
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);
Mike Sherov
Uhh, I don't think you want your for-loop to just return the tag element. Don't you want to build a new list of tags, and return that?
Pointy
good point... fixed
Mike Sherov
+1  A: 

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);
Mark Byers
+1 beat me to the regexp version although i used a function as the replacement string which copied the matches to another string..
Gaby
That is indeed a crazy regex. :) Thanks for the great answer!
Travis
I believe the regex could be simplified to: `(^|\b)\w*blu\w*(; |$)`
Dave Ward