atc
atc

Reputation: 621

string comparison and remove common values using jquery

I have a numeric string like this

str1 = '12,13,14,15';
str2 = '13,15';

I just want to compare two strings and need to remove common integers from string.

For eg: I just want to remove 13 & 15 from first string and return remaining values. is it possible in jquery ? (Str1 & str2 can contain so many values,its a dynamic set)

I have started with like this.I am basically spliiting second string here

var match = str2.split(',');


    for (var a in match){

       var variable = match[a]
}

Upvotes: 0

Views: 1431

Answers (3)

user2019037
user2019037

Reputation: 762

One solution is to use them as arrays and use js filter and indexOf:

str1 = new Array('12','13','14','15');
str2 = new Array('13','15');

str1 = str1.filter(function(val) {
  return str2.indexOf(val) == -1;
});

document.write(str1);

Upvotes: 1

Stefan Koenen
Stefan Koenen

Reputation: 2337

You can use some jQuery for this;

var str1 = '12,13,14,15';
var str2 = '13,15';

var array1 = str1.split(',');
var array2 = str2.split(',');

// filtered below
array1 = $(array1).not(array2).get();

JSFiddle

Upvotes: 1

elzi
elzi

Reputation: 5672

Get them into arrays then filter. Here's an (overlay verbose) attempt:

function compareStringsRemoveDuplicates(string1, string2) {

    var string1 = string1 || '',  
        string2 = string2 || '';

    var string1Array = string1.split(',');
    var string2Array = string2.split(',');

    string1Array = string1Array.filter(function (val) {
      return string2Array.indexOf(val) == -1;
    });
}      

var newString = compareStringsRemoveDuplicates('12,13,14,15', '13, 15');

Upvotes: 1

Related Questions