Rachel
Rachel

Reputation: 1159

How to remove this special characters and how to avoid duplication in string variable value?

I have java script string variable with some special characters and duplicate values... i want to remove only the < and > symbols and need to avoid duplicates... how to achieve this...

this is what i have...

var columnname = "USER_ID,PRIORITY,CREATION_DATE<,CREATION_DATE>,ASSIGN_TO_USER_DATE<,ASSIGN_TO_USER_DATE>,START_WORK_DATE<,START_WORK_DATE>,PARTICIPANT_TYPE,SENDER_ID";

and it should be like this....

var columnname = "USER_ID,PRIORITY,CREATION_DATE,ASSIGN_TO_USER_DATE,START_WORK_DATE,PARTICIPANT_TYPE,SENDER_ID";

Upvotes: 0

Views: 436

Answers (3)

AlexMost
AlexMost

Reputation: 104

Also you may use reduce function

    input_string.replace(/[<>]/g, "").split(",").reduce(function(a, b) {
        a = Array.isArray(a)? a : [a];
        if(a.indexOf(b) == -1){ a.push(b);}
        return a;
    });

Upvotes: 0

epoch
epoch

Reputation: 16595

I am not giving the full answer as you have not provided any code, but here are the basic steps you should follow:

  • replace all unwanted characters in the string
  • split the string on the comma to give you an array of values
  • take out all the duplicates out of the array

Upvotes: 0

VisioN
VisioN

Reputation: 145388

One possible short solution:

columnname.replace(/[<>]/g, "").split(",").filter(function(item, i, arr) {
    return i === arr.indexOf(item);
}).join(",");

Note, that some old browsers might not support Array.filter() and Array.indexOf() methods. You may check for compatibility shims in MDN.

Upvotes: 3

Related Questions