2013-04-25 19 views
9

ho stringhe in jQuery:Ottenere secondo e terzo parole da stringa

var string1 = 'Stack Exchange premium'; 
var string2 = 'Similar Questions'; // only two 
var string3 = 'Questions that may already have your answer'; 

Come posso ottenere da questo secondo e terzo parole?

var second1 = ???; 
var third1 = ???; 
var second2 = ???; 
var third2 = ???; 
var second3 = ???; 
var third3 = ???; 
+3

È necessario aggiungere il codice alla domanda. Che cosa hai provato e perché non ha funzionato? – andrewsi

+2

Quando le persone hanno problemi con JavaScript, dicono che è un problema jQuery, anche se il problema non riguarda affatto jQuery. – xfix

risposta

7

Innanzitutto, non hai stringhe e variabili "in jQuery". jQuery non ha nulla a che fare con questo.

In secondo luogo, modificare la struttura dei dati, in questo modo:

var strings = [ 
    'Stack Exchange premium', 
    'Similar Questions', 
    'Questions that may already have your answer' 
]; 

Poi creare un nuovo array con il secondo e terzo parole.

var result = strings.map(function(s) { 
    return s.split(/\s+/).slice(1,3); 
}); 

Ora è possibile accedere ogni parola in questo modo:

console.log(result[1][0]); 

Questo vi darà la prima parola del secondo risultato.

14

Usa stringa split() per dividere la stringa da spazi:

var words = string1.split(' '); 

quindi accedere alla parole utilizzando:

var word0 = words[0]; 
var word1 = words[1]; 
// ... 
+0

Non dovresti incoraggiare l'OP a usare variabili come 'word0',' word1', 'wordXXX' ecc. –

+2

@LeeTaylor È solo un esempio – hek2mgl

2
var temp = string1.split(" ")//now you have 3 words in temp 
temp[1]//is your second word 
temp[2]// is your third word 

è possibile controllare quante parole hai da temperatura .length

3

Solo per aggiungere alle possibili soluzioni, la tecnica che utilizza split() avrà esito negativo se la stringa contiene più spazi.

var arr = " word1 word2 ".split(' ') 

//arr is ["", "", "", "word1", "", "", "word2", "", "", "", ""] 

Per evitare questo problema, l'uso seguente

var arr = " word1 word2 ".match(/\S+/gi) 

//arr is ["word1", "word2"] 

e poi la solita,

var word1 = arr[0]; 
var word2 = arr[1] 
//etc 

anche non dimenticate di controllare la lunghezza dell'array utilizzando .length proprietà per evitare di ottenere undefined nelle tue variabili.

Problemi correlati