2016-11-04 1 views
1
var myStr = "I love chocolate and strawberry, love this and that as well, and again love walking along the street"; 

var newStr = myStr.substr(myStr.indexOf('love'), myStr.lastIndexOf('love')); 

///" chocolate and strawberry, "; //this is the output 

get substring entre deux indices en utilisant indexOf()

var myStr = "I love chocolate and strawberry, love this and that as well, and again love walking along the street"; 
 
    
 
    var newStr = myStr.substr(myStr.indexOf('love'), myStr.lastIndexOf('love')); 
 

 
console.log(newStr);

Comment puis-je obtenir le texte entre le premier mot « amour » et le second mot « amour » qui devrait être "chocolat et la fraise, "?

+1

'String.indexOf()' prend en charge deuxième param, 'fromIndex' [(doc)] (https://developer.mozilla.org/en/docs/Web/JavaScript/ Référence/Global_Objects/String/indexOf). Si vous stockez le résultat du premier 'indexOf', il suffit de le réutiliser. – raina77ow

Répondre

1

Vous pouvez split votre chaîne avec love :) et regardez le deuxième élément dans le tableau:

var newStr = myStr.split("love")[1]; 
1

Utilisez String#substring et String#indexOf méthode avec l'argument fromIndex.

var myStr = "I love chocolate and strawberry, love this and that as well, and again love walking along the street"; 
 
var str='love', ind = myStr.indexOf(str); 
 
var newStr = myStr.substring(ind + str.length , myStr.indexOf(str,ind + 1)); 
 

 
console.log(newStr);

0

je d'accord avec la réponse ci-dessus, mais si vous voulez savoir comment obtenir l'indice de seconde « Love », vous pouvez passer le « startingPostion » dans indexOf(), il va chercher le mot "Love" après la position de départ.

0

Le problème que vous rencontrez est dû au fait que le deuxième index que vous envoyez à la méthode de sous-chaîne est le début du dernier mot «amour» et non la fin de celui-ci ... Si vous ajoutez la longueur du mot «amour» au deuxième index, votre code devrait fonctionner très bien.

0

Enveloppez-vous dans une fonction pour une utilisation facile. Il suffit d'appeler getTextBetween(splitOnString, middleTextDesired) sur votre chaîne.

splitOnString est le texte que vous voulez regarder.

middleTextDesired est le numéro du texte intermédiaire souhaité. 1 pour le 1er, 2 pour le 2ème, etc ...

Ce n'est pas une fonction finie car les contrôles défensifs ne sont pas ajoutés, mais l'idée est claire.

var myStr = "I love chocolate and strawberry, love this and that as well, and again love walking along the street"; 
 
    
 
String.prototype.getTextBetween = function(splitOn, middleTextDesired = 1) { 
 
    return this.split(splitOn)[middleTextDesired]; 
 
} 
 

 
console.log(myStr.getTextBetween('love', 1));