2

I am appending the .text() of an anchor to an input when its dragged and dropped to it.

The thing is that I need them comma sepated and not repeated:

If I am tying to add 'string 1' to the input when the value is already 'bla, ble, string1', I need to prevent to be duplicated,

How would you do it?

My first guess is to make an explode by ',' and combine it with a for loop, but I don't think that is really optimized at all.

epascarello
  • 204,599
  • 20
  • 195
  • 236
Toni Michel Caubet
  • 19,333
  • 56
  • 202
  • 378
  • Why not use a regex to match `string1` between two commas? Of course you'd need to account for it being first or last element too when building your regex. – Aleks G Jan 27 '12 at 14:03
  • 1
    BTW, is there a good reason why you need to store a big string? Why don't you keep the easier to manipulate "exploded" array instead? – hugomg Jan 27 '12 at 14:13
  • http://stackoverflow.com/questions/890782/javascript-function-inarray – Stefan Jan 27 '12 at 14:15

4 Answers4

2

Basic Idea

function addParameter(str, param) {
    var re = new RegExp("[^,]\\s?" + param + "[,$]","g");
    if( !re.test(str) ) {
        str += ( (str.length>0) ? ", " : "") + param;
    }
    return str;
}

var orgStr = "abc, def, hij";

//This exists so it will not be added
var newStr = addParameter( orgStr, "def" );
console.log( newStr );

//This does not exist so it will be added to the end
newStr = addParameter( orgStr, "xyz" );
console.log( newStr );

Explain Regular Expression

  • [^,]\\s? - Says match beginning of string or a comma followed by an optional space character
  • param - matches your string passed in
  • [,$] - Says match a comma or the end of a string.
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

Convert your existing CSV string to an array, append your value, and then convert it back to a string:

//Create an array from the CSV list
var myVals = $("#YourElement").val().split(",");
var isDupe = false;

for(var i = 0; i < myVals.length; i++) {
    if(myVals[i].indexOf("YourNewValue") != -1) {
        isDupe = true;
        break;
    }
}

//use .push() to append your value to the end of the array
if(!isDupe) {
    myVals.push("YourNewValue");

    //Invoking .toString() on an array creates a CSV list
    $("#YourElement").val(myVals.toString());
}

Here's a working fiddle.

James Hill
  • 60,353
  • 20
  • 145
  • 161
0

Based on your fiddle you can;

var myVals = $("#YourElement").val().split(",");
var wantToAdd = "cakey";

if ($.inArray(wantToAdd, myVals) === -1)
   myVals.push(wantToAdd);

$("#YourElement").val(myVals.join(","));
Alex K.
  • 171,639
  • 30
  • 264
  • 288
0

I don't see the need for reg exp or array-

var t=input.value, s= //text string;
if(t.indexOf(s)==-1)t.value=t+ ', '+s;
kennebec
  • 102,654
  • 32
  • 106
  • 127