Come posso dividere una stringa, interrompendola in un particolare carattere?
-
01-07-2019 - |
Domanda
Ho questa corda
'john smith~123 Street~Apt 4~New York~NY~12345'
Utilizzando JavaScript, qual è il modo più veloce per analizzarlo
var name = "john smith";
var street= "123 Street";
//etc...
Soluzione
Con JavaScript String.prototype.split
funzione:
var input = 'john smith~123 Street~Apt 4~New York~NY~12345';
var fields = input.split('~');
var name = fields[0];
var street = fields[1];
// etc.
Altri suggerimenti
Non hai bisogno di jQuery.
var s = 'john smith~123 Street~Apt 4~New York~NY~12345';
var fields = s.split(/~/);
var name = fields[0];
var street = fields[1];
Secondo ECMAScript6 ES6
, il modo pulito è distruggere gli array:
const input = 'john smith~123 Street~Apt 4~New York~NY~12345';
const [name, street, unit, city, state, zip] = input.split('~');
console.log(name); // john smith
console.log(street); // 123 Street
console.log(unit); // Apt 4
console.log(city); // New York
console.log(state); // NY
console.log(zip); // 12345
Potresti avere elementi aggiuntivi nella stringa di input.In questo caso, puoi utilizzare l'operatore rest per ottenere un array per il resto o semplicemente ignorarlo:
const input = 'john smith~123 Street~Apt 4~New York~NY~12345';
const [name, street, ...others] = input.split('~');
console.log(name); // john smith
console.log(street); // 123 Street
console.log(others); // ["Apt 4", "New York", "NY", "12345"]
Supponevo un riferimento di sola lettura per i valori e ho usato il file const
dichiarazione.
Divertiti con ES6!
Anche se questo non è il modo più semplice, potresti farlo:
var addressString = "~john smith~123 Street~Apt 4~New York~NY~12345~",
keys = "name address1 address2 city state zipcode".split(" "),
address = {};
// clean up the string with the first replace
// "abuse" the second replace to map the keys to the matches
addressString.replace(/^~|~$/g).replace(/[^~]+/g, function(match){
address[ keys.unshift() ] = match;
});
// address will contain the mapped result
address = {
address1: "123 Street"
address2: "Apt 4"
city: "New York"
name: "john smith"
state: "NY"
zipcode: "12345"
}
Aggiornamento per ES2015, utilizzando la destrutturazione
const [address1, address2, city, name, state, zipcode] = addressString.match(/[^~]+/g);
// The variables defined above now contain the appropriate information:
console.log(address1, address2, city, name, state, zipcode);
// -> john smith 123 Street Apt 4 New York NY 12345
beh, il modo più semplice sarebbe qualcosa del tipo:
var address = theEncodedString.split(/~/)
var name = address[0], street = address[1]
Se È stato trovato lo splitter solo allora
Dividilo
altrimenti restituisci il stessa corda
function SplitTheString(ResultStr) { if (ResultStr != null) { var SplitChars = '~'; if (ResultStr.indexOf(SplitChars) >= 0) { var DtlStr = ResultStr.split(SplitChars); var name = DtlStr[0]; var street = DtlStr[1]; } } }
Qualcosa di simile a:
var divided = str.split("/~/");
var name=divided[0];
var street = divided[1];
Probabilmente sarà più semplice
Puoi usare split
per dividere il testo.
In alternativa è possibile utilizzare anche match
come segue
var str = 'john smith~123 Street~Apt 4~New York~NY~12345';
matches = str.match(/[^~]+/g);
console.log(matches);
document.write(matches);
La regex [^~]+
corrisponderà a tutti i caratteri tranne ~
e restituisce le corrispondenze in un array.È quindi possibile estrarre le corrispondenze da esso.
Zach aveva ragione su questo...usando il suo metodo potresti anche creare un array apparentemente "multidimensionale".Ho creato un rapido esempio su JSFiddle http://jsfiddle.net/LcnvJ/2/
// array[0][0] will produce brian
// array[0][1] will produce james
// array[1][0] will produce kevin
// array[1][1] will produce haley
var array = [];
array[0] = "brian,james,doug".split(",");
array[1] = "kevin,haley,steph".split(",");
Questo string.split("~")[0];
fa le cose.
fonte: String.prototipo.split()
Un altro approccio funzionale che utilizza curry e composizione funzionale.
Quindi la prima cosa sarebbe la funzione di divisione.Vogliamo farlo "john smith~123 Street~Apt 4~New York~NY~12345"
in questo ["john smith", "123 Street", "Apt 4", "New York", "NY", "12345"]
const split = (separator) => (text) => text.split(separator);
const splitByTilde = split('~');
Quindi ora possiamo usare il nostro specializzato splitByTilde
funzione.Esempio:
splitByTilde("john smith~123 Street~Apt 4~New York~NY~12345") // ["john smith", "123 Street", "Apt 4", "New York", "NY", "12345"]
Per ottenere il primo elemento possiamo usare il list[0]
operatore.Costruiamo un first
funzione:
const first = (list) => list[0];
L'algoritmo è:diviso dai due punti e quindi ottieni il primo elemento dell'elenco fornito.Quindi possiamo comporre quelle funzioni per costruire il nostro finale getName
funzione.Costruendo un compose
funzionare con reduce
:
const compose = (...fns) => (value) => fns.reduceRight((acc, fn) => fn(acc), value);
E ora lo uso per comporre splitByTilde
E first
funzioni.
const getName = compose(first, splitByTilde);
let string = 'john smith~123 Street~Apt 4~New York~NY~12345';
getName(string); // "john smith"
Poiché la domanda sulla suddivisione in virgole è duplicata in questa domanda, aggiungila qui.
Se vuoi dividere un carattere e gestire anche gli spazi bianchi extra che potrebbero seguire quel carattere, cosa che spesso accade con le virgole, puoi usare replace
Poi split
, come questo:
var items = string.replace(/,\s+/, ",").split(',')
Prova in Javascript semplice
//basic url=http://localhost:58227/ExternalApproval.html?Status=1
var ar= [url,statu] = window.location.href.split("=");
Usa questo codice --
function myFunction() {
var str = "How are you doing today?";
var res = str.split("/");
}