0

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]
}
0

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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');

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.