web-dev-qa-db-fra.com

couper une partie d'une chaîne

Dis, j'ai une chaîne

"hello is it me you're looking for"

Je veux couper une partie de cette chaîne et retourner la nouvelle chaîne, quelque chose comme

s = string.cut(0,3);

s serait désormais égal à:

"lo is it me you're looking for"

EDIT : Il peut ne pas être de 0 à 3. Il peut être de 5 à 7.

s = string.cut(5,7);

retournerais

"hellos it me you're looking for"
21
dotty

Tu y es presque. Ce que vous voulez c'est:

http://www.w3schools.com/jsref/jsref_substr.asp

Donc, dans votre exemple:

Var string = "hello is it me you're looking for";
s = string.substr(3);

Comme fournir uniquement un début (le premier argument) prend de cet index jusqu'à la fin de la chaîne.

Mise à jour, que diriez-vous de quelque chose comme:

function cut(str, cutStart, cutEnd){
  return str.substr(0,cutStart) + str.substr(cutEnd+1);
}
33
Jake

Utilisation

sous-chaîne

fonction

Renvoie un sous-ensemble d'une chaîne entre un index et un autre, ou jusqu'à la fin de la chaîne.

substring(indexA, [indexB]);

indexA

An integer between 0 and one less than the length of the string. 

indexB (facultatif) Un entier entre 0 et la longueur de la chaîne.

la sous-chaîne extrait les caractères de l'indexA jusqu'à mais n'inclut pas l'indexB. En particulier:

* If indexA equals indexB, substring returns an empty string.
* If indexB is omitted, substring extracts characters to the end 
  of the string.
* If either argument is less than 0 or is NaN, it is treated as if 
  it were 0.
* If either argument is greater than stringName.length, it is treated as 
  if it were stringName.length.

Si indexA est plus grand que indexB, alors l'effet de la sous-chaîne est comme si les deux arguments étaient échangés; par exemple, str.substring (1, 0) == str.substring (0, 1).

8
rahul
s = string.cut(5,7);

Je préfère le faire comme une fonction distincte, mais si vous voulez vraiment pouvoir l'appeler directement sur une chaîne du prototype:

String.prototype.cut= function(i0, i1) {
    return this.substring(0, i0)+this.substring(i1);
}
4
bobince

string.substring () est ce que vous voulez.

3
Cheeso

Quelques autres alternatives plus modernes sont:

  1. Fractionner et rejoindre

    function cutFromString(oldStr, fullStr) {
      return fullStr.split(oldStr).join('');
    }
    cutFromString('there ', 'Hello there world!'); // "Hello world!"
    

    Adapté de exemple MDN

  2. String.replace () , qui utilise l'expression régulière. Cela signifie qu'il peut être plus flexible avec une sensibilité à la casse.

    function cutFromString(oldStrRegex, fullStr) {
      return fullStr.replace(oldStrRegex, '');
    }
    cutFromString(/there /i , 'Hello THERE world!'); // "Hello world!"
    
3
filoxo

À titre de référence pour tous ceux qui recherchent une fonction similaire, j'ai une implémentation String.prototype.bisect qui divise une chaîne à 3 voies à l'aide d'un délimiteur regex/string et retourne les parties avant, délimiteur-correspondance et après de la chaîne ... .

/*
      Splits a string 3-ways along delimiter.
      Delimiter can be a regex or a string.
      Returns an array with [before,delimiter,after]
*/
String.prototype.bisect = function( delimiter){
  var i,m,l=1;
  if(typeof delimiter == 'string') i = this.indexOf(delimiter);
  if(delimiter.exec){
     m = this.match(delimiter);
     i = m.index;
     l = m[0].length
  }
  if(!i) i = this.length/2;
  var res=[],temp;
  if(temp = this.substring(0,i)) res.Push(temp);
  if(temp = this.substr(i,l)) res.Push(temp);
  if(temp = this.substring(i+l)) res.Push(temp);
  if(res.length == 3) return res;
  return null;
};

/* though one could achieve similar and more optimal results for above with: */

"my string to split and get the before after splitting on and once".split(/and(.+)/,2) 

// outputs => ["my string to split ", " get the before after splitting on and once"]

Comme indiqué ici: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/String/split

Si le séparateur est une expression régulière qui contient des parenthèses de capture, chaque fois que le séparateur est mis en correspondance, les résultats (y compris les résultats non définis) des parenthèses de capture sont épissés dans le tableau de sortie. Cependant, tous les navigateurs ne prennent pas en charge cette fonctionnalité.

1
Quickredfox

Vous devez faire quelque chose comme ceci:

var s = "I am a string";

var sSubstring = s.substring(2); // sSubstring now equals "am a string".

Vous avez deux options sur la façon de procéder:

http://www.quirksmode.org/js/strings.html#substring

http://www.quirksmode.org/js/strings.html#substr

0
kemiller2002

Essayez ce qui suit:

var str="hello is it me you're looking for";
document.write(str.substring(3)+"<br />");

Vous pouvez vérifier ce lien

0
Himadri