2009-08-20 2 views
12

Ho una stringa csv come questa "1,2,3" e voglio essere in grado di rimuovere un valore desiderato da esso.rimuovere il valore dai valori separati da virgola stringa

Per esempio se voglio rimuovere il valore: 2, la stringa di uscita dovrebbe essere il seguente:

"1,3"

Sto utilizzando il seguente codice, ma sembra essere inefficace.

var values = selectedvalues.split(","); 
      if (values.length > 0) { 
       for (var i = 0; i < values.length; i++) { 
        if (values[i] == value) { 
         index = i; 
         break; 
        } 
       } 
       if (index != -1) { 
        selectedvalues = selectedvalues.substring(0, index + 1) + selectedvalues.substring(index + 3);      
       } 
      } 
      else { 
       selectedvalues = ""; 
      } 

risposta

37
var removeValue = function(list, value, separator) { 
    separator = separator || ","; 
    var values = list.split(separator); 
    for(var i = 0 ; i < values.length ; i++) { 
    if(values[i] == value) { 
     values.splice(i, 1); 
     return values.join(separator); 
    } 
    } 
    return list; 
} 

Se viene rilevato il valore che stai cercando, viene rimossa, e un nuovo virgole lista delimitata restituiti. Se non viene trovato, viene restituita la vecchia lista.

Grazie a Grant Wagner per indicare il mio errore di codice e il miglioramento!

John Dimigne (jQuery, Mozilla) ha un articolo accurato su JavaScript Array Remove che potrebbe risultare utile.

+0

Perché il down vota? – doomspork

+0

Probabilmente sei downvoted perché 'selectedValues.split (", ")' restituisce un array, gli array non hanno un metodo 'indexOf()' in JavaScript. –

+0

Lei signore, ha ragione! Grazie per avermelo fatto notare – doomspork

1

valori è ora una matrice. Quindi, invece di fare il traversamento te stesso.

fare:

var index = values.indexOf(value); 
if(index >= 0) { 
    values.splice(index, 1); 
} 

rimozione di un singolo oggetto da un determinato indice.

Spero che questo aiuti

+0

BTW. per ottenere di nuovo l'array in una stringa ... basta fare: var somstring = values.join (','); – Jabezz

+1

@Jabezz: non riesce quando 'value' è" 1,12,2 "e si desidera rimuovere" 2 ". –

0
function process(csv,valueToDelete) { 
    var tmp = ","+csv; 
    tmp = tmp.replace(","+valueToDelete,""); 
    if (tmp.substr(0,1) == ',') tmp = tmp.substr(1); 
    return tmp; 
} 
+0

C'è un bug! Il processo di chiamata ('1,2,3,25,29,36', 2) restituirà "1,3,5,9,36" quando dovrebbe restituire "1,3,25,29,36". – LukeH

2

Qui ci sono 2 possibili soluzioni:

function removeValue(list, value) { 
    return list.replace(new RegExp(value + ',?'), '') 
} 

function removeValue(list, value) { 
    list = list.split(','); 
    list.splice(list.indexOf(value), 1); 
    return list.join(','); 
} 

removeValue('1,2,3', '2'); // "1,3" 

Si noti che questo rimuoverà solo la prima occorrenza di un valore.

Si noti inoltre che Array.prototype.indexOf non fa parte di ECMAScript ed. 3 (è stato introdotto in JavaScript 1.6 - implementato in tutte le moderne implementazioni eccetto JScript - ed è ora codificato in ES5).

+1

Anche il primo esempio fallirà anche. 22, 32, 42, ecc. Quindi questa risposta non è una risposta. – epascarello

+4

Vedere la risposta di Doomspork (http://stackoverflow.com/questions/1306164/1306225#1306225) per ciò che sembra essere un'implementazione corretta. –

+0

Funziona se ci sono più valori da rimuovere? – Breakthrough

1
// Note that if the source is not a proper CSV string, the function will return a blank string (""). 
function removeCsvVal(var source, var toRemove)  //source is a string of comma-seperated values, 
{             //toRemove is the CSV to remove all instances of 
    var sourceArr = source.split(",");    //Split the CSV's by commas 
    var toReturn = "";        //Declare the new string we're going to create 
    for (var i = 0; i < sourceArr.length; i++)  //Check all of the elements in the array 
    { 
     if (sourceArr[i] != toRemove)    //If the item is not equal 
      toReturn += sourceArr[i] + ",";   //add it to the return string 
    } 
    return toReturn.substr(0, toReturn.length - 1); //remove trailing comma 
} 

per applicarlo anche i valori var:

var values = removeVsvVal(selectedvalues, "2"); 
1

indovinare im troppo lento, ma qui è quello che vorrei fare

<script language="javascript"> 
function Remove(value,replaceValue) 
{ var result = ","+value+","; 
result = result.replace(","+replaceValue+",",","); 
result = result.substr(1,result.length); 
result = result.substr(0,result.length-1); 
alert(result); 
} 

Remove("1,2,3",2) 
</script> 

aggiungendo, prima e dopo la stringa in modo che u rimuovere solo la stringa esatta u vuole

0

uso giunzione, pop o spostamento. secondo il vostro requisito

Si potrebbe anche avere "trovare" gli indici delle voci nella propria matrice quella partita, utilizzando una funzione come quella che si trova qui: http://www.hunlock.com/blogs/Ten_Javascript_Tools_Everyone_Should_Have

var tmp = [5,9,12,18,56,1,10,42,'blue',30, 7,97,53,33,30,35,27,30,'35','Ball', 'bubble']; 
//   0/1/2 /3 /4/5 /6 /7  /8 /9/10/11/12/13/14/15/16/17/ 18/ 19/  20 
var thirty=tmp.find(30);    // Returns 9, 14, 17 
var thirtyfive=tmp.find('35');  // Returns 18 
var thirtyfive=tmp.find(35);   // Returns 15 
var haveBlue=tmp.find('blue');  // Returns 8 
var notFound=tmp.find('not there!'); // Returns false 
var regexp1=tmp.find(/^b/);   // returns 8,20 (first letter starts with b) 
var regexp1=tmp.find(/^b/i);   // returns 8,19,20 (same as above but ignore case) 

Array.prototype.find = function(searchStr) { 
    var returnArray = false; 
    for (i=0; i<this.length; i++) { 
    if (typeof(searchStr) == 'function') { 
     if (searchStr.test(this[i])) { 
     if (!returnArray) { returnArray = [] } 
     returnArray.push(i); 
     } 
    } else { 
     if (this[i]===searchStr) { 
     if (!returnArray) { returnArray = [] } 
     returnArray.push(i); 
     } 
    } 
    } 
    return returnArray; 
} 
+0

Va sottolineato che il metodo find sta modificando il metodo Prototipo di array che può essere meno desiderabile per alcuni sviluppatori. I suoi effetti possono irradiarsi oltre lo scopo previsto. – doomspork

6
function removeValue(list, value) { 
    return list.replace(new RegExp(",?" + value + ",?"), function(match) { 
     var first_comma = match.charAt(0) === ',', 
      second_comma; 

     if (first_comma && 
      (second_comma = match.charAt(match.length - 1) === ',')) { 
     return ','; 
     } 
     return ''; 
    }); 
}; 


alert(removeValue('1,2,3', '1')); // 2,3 
alert(removeValue('1,2,3', '2')); // 1,3 
alert(removeValue('1,2,3', '3')); // 1,2 
+0

questo codice non funzionerà con removeValue ('1,25,3', '2') – Rajapandian

0

o

var csv_remove_val = function(s, val, sep) { 
    var sep = sep || ",", a = s.split(sep), val = ""+val, pos; 
    while ((pos = a.indexOf(val)) >= 0) a.splice(pos, 1); 
    return a.join(sep); 
}