Javascript string replacement

I have a string of tags separated by semicolons:

"red; yellow; blue; green; purple"

I would like to remove all tags that do not match the substring (case insensitive.)

For example, if I have the substring "Bl", I would like to return "blue".

Any suggestions on how best to accomplish this in javascript? In particular, I am wondering if there is one step for this in regex ...

Thanks in advance!

+3
source share
3 answers

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 mainly described by Simon with one additional step - a joinat the end, to convert the result back to a string.

, . : , . , :

var s = 'red; yellow; blue; geen; purple';
var result = ('; ' + s).replace(/;(?![^;]*blu)[^;]*(?=;|$)/g, '').substring(2);
alert(result);
+1

, split(), match indexOf . , , toLowerCase .

+2
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);
0

Source: https://habr.com/ru/post/1731717/


All Articles