Comment renvoyer une partie de la chaîne après un certain caractère?

Si vous regardez le jsfiddle de la question ,

var str = "Abc: Lorem ipsum sit amet"; str = str.substring(str.indexOf(":") + 1); 

Cela renvoie tous les caractères après le : comment puis-je l'ajuster pour renvoyer tous les caractères avant :

Quelque chose comme var str_sub = str.substr(str.lastIndexOf(":")+1); Mais cela ne fonctionne pas.

Vous jouez déjà au travail … peut-être que vous essayez d'obtenir la chaîne avant le double colon? (Vous devriez vraiment modifier votre question) Ensuite, le code serait comme ceci:

str.substring(0, str.indexOf(":"));

Où 'str' représente la variable avec votre chaîne à l'intérieur.

Cliquez ici pour l'exemple JSFiddle

Javascript

 var input_string = document.getElementById('my-input').innerText; var output_element = document.getElementById('my-output'); //here we go var right_text = input_string.substring(0, input_string.indexOf(":")); output_element.innerText = right_text; 

Html

 <p> <h5>Input:</h5> <strong id="my-input">Left Text:Right Text</strong> <h5>Output:</h5> <strong id="my-output">XXX</strong> </p> 

CSS

 body { font-family: Calibri, sans-serif; color:#555; } h5 { margin-bottom: 0.8em; } strong { width:90%; padding: 0.5em 1em; background-color: cyan; } #my-output { background-color: gold; } 

Une autre méthode pourrait être de diviser la chaîne par ":" et de sortir de la fin. var newString = string.split(":").pop();

Et notez que le premier argument de subString est basé sur 0, tandis que le second est basé sur.

Exemple:

 String str= "0123456"; String sbstr= str.substring(0,5); 

La sortie sera sbstr= 01234 et non sbstr = 012345