Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript String Replace

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!

like image 326
Travis Avatar asked May 25 '26 14:05

Travis


2 Answers

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.

like image 91
Simon Groenewolt Avatar answered May 27 '26 03:05

Simon Groenewolt


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);
like image 37
Mark Byers Avatar answered May 27 '26 02:05

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!