Méthodes de chaîne JavaScript


Table des matières

    Afficher la table des matières

String length
String slice()
String substring()
String substr()
String replace()
String replaceAll()
String toUpperCase()
String toLowerCase()
String concat()
String trim()
String trimStart()
String trimEnd()
String padStart()
String padEnd()
String charAt()
String charCodeAt()
String split()

Note

Les méthodes de recherche de chaîne sont abordées dans le chapitre suivant.


Longueur de la chaîne JavaScript

La propriété length renvoie la longueur d'une chaîne :

Exemple

let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The length Property</h2>

<p>The length of the string is:</p>
<p id="demo"></p>

<script>
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.getElementById("demo").innerHTML = text.length;
</script>

</body>
</html>


Extraction de parties de chaîne

Il existe 3 méthodes pour extraire une partie d'une chaîne :

  • slice(start, end)
  • substring(start, end)
  • substr(start, length)

Tranche de chaîne JavaScript()

slice() extrait une partie d'une chaîne et renvoie le partie extraite dans une nouvelle chaîne.

La méthode prend 2 paramètres : la position de départ et la position de fin (fin non incluse).

Exemple

Découpez une partie d'une chaîne de la position 7 à la position 13 :

let text = "Apple, Banana, Kiwi";
let part = text.slice(7, 13);

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The slice() Method</h2>

<p>The sliced (extracted) part of the string is:</p>
<p id="demo"></p>

<script>
let text = "Apple, Banana, Kiwi";
let part = text.slice(7,13);
document.getElementById("demo").innerHTML = part; 
</script>

</body>
</html>


Note

JavaScript compte les positions à partir de zéro.

La première position est 0.

La deuxième position est 1.

Exemples

Si vous omettez le deuxième paramètre, la méthode supprimera le reste de la chaîne :

let text = "Apple, Banana, Kiwi";
let part = text.slice(7);

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The slice() Method</h2>

<p>Extract a part of a string from position 7:</p>
<p id="demo"></p>

<script>
let text = "Apple, Banana, Kiwi";
let part = text.slice(7)
document.getElementById("demo").innerHTML = part;
</script>

</body>
</html>


Si un paramètre est négatif, la position est comptée à partir de la fin de la chaîne :

let text = "Apple, Banana, Kiwi";
let part = text.slice(-12);

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The slice() Method</h2>

<p>Extract a part of a string counting from the end:</p>
<p id="demo"></p>

<script>
let text = "Apple, Banana, Kiwi";
let part = text.slice(-12);
document.getElementById("demo").innerHTML = part;
</script>

</body>
</html>


Cet exemple découpe une partie d'une chaîne de la position -12 à la position -6 :

let text = "Apple, Banana, Kiwi";
let part = text.slice(-12, -6);

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The slice() Method</h2>

<p>Extract a part of a string and return the extracted parts in a new string:</p>

<p id="demo"></p>

<script>
let text = "Apple, Banana, Kiwi";
let part = text.slice(-12,-6)
document.getElementById("demo").innerHTML = part;
</script>

</body>
</html>




Sous-chaîne de chaîne JavaScript()

substring() est similaire à slice().

La différence est que les valeurs de début et de fin inférieures à 0 sont traitées comme 0 dans sous-chaîne().

Exemple

let str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Methods</h1>
<p>The substring() method extract a part of a string and returns the extracted parts in a new string:</p>

<p id="demo"></p>

<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.substring(7,13);
</script>

</body>
</html>

Si vous omettez le deuxième paramètre, substring() supprimera le reste du chaîne.


Chaîne JavaScript substr()

substr() est similaire à slice().

La différence est que le deuxième paramètre spécifie la longueur de la partie extraite.

Exemple

let str = "Apple, Banana, Kiwi";
let part = str.substr(7, 6);

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Methods</h1>
<p>The substr() method extract a part of a string
and returns the extracted parts in a new string:</p>

<p id="demo"></p>

<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.substr(7,6);
</script>

</body>
</html>


Si vous omettez le deuxième paramètre, substr() supprimera le reste du chaîne.

Exemple

let str = "Apple, Banana, Kiwi";
let part = str.substr(7);

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Methods</h1>
<p>The substr() method extract a part of a string and returns the extracted parts in a new string:</p>

<p id="demo"></p>

<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.substr(7);
</script>

</body>
</html>


Si le premier paramètre est négatif, la position compte à partir de la fin du chaîne.

Exemple

let str = "Apple, Banana, Kiwi";
let part = str.substr(-4);

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Methods</h1>
<p>The substr() method extract a part of a string and returns the extracted parts in a new string:</p>

<p id="demo"></p>

<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.substr(-4);
</script>

</body>
</html>



Remplacement du contenu d'une chaîne

La méthode replace() remplace une valeur spécifiée par une autre valeur dans une chaîne :

Exemple

let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");

Essayez-le vous-même →

<!DOCTYPE html>
<html>

<body>

<h1>JavaScript String Methods</h1>
<p>Replace &quot;Microsoft&quot; with &quot;W3Schools&quot; in the paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Please visit Microsoft!</p>

<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML;
  document.getElementById("demo").innerHTML =
  text.replace("Microsoft","W3Schools");
}
</script>

</body>
</html>


Note

La méthode replace() ne modifie pas la chaîne sur laquelle elle est appelée.

La méthode replace() renvoie une nouvelle chaîne.

La méthode replace() remplace uniquement la première correspondance

Si vous souhaitez remplacer toutes les correspondances, utilisez une expression régulière avec l'indicateur /g défini. Voir les exemples ci-dessous.

Par défaut, la méthode replace() remplace uniquement la première correspondance :

Exemple

let text = "Please visit Microsoft and Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Methods</h1>
<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Please visit Microsoft and Microsoft!</p>

<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML; 
  document.getElementById("demo").innerHTML =
  text.replace("Microsoft","W3Schools");
}
</script>

</body>
</html>


Par défaut, la méthode replace() est sensible à la casse. Ecriture de MICROSOFT (avec majuscules) ne fonctionnera pas :

Exemple

let text = "Please visit Microsoft!";
let newText = text.replace("MICROSOFT", "W3Schools");

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Methods</h1>
<p>Try to replace "Microsoft" with "W3Schools" in the paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Please visit Microsoft!</p>

<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML; 
  document.getElementById("demo").innerHTML =
  text.replace("MICROSOFT","W3Schools");
}
</script>

<p>The replace() method is case sensitive. MICROSOFT (with upper-case) will not be replaced.</p>

</body>
</html>

Pour remplacer la casse, utilisez une expression régulière avec un indicateur /i (insensible) :

Exemple

let text = "Please visit Microsoft!";
let newText = text.replace(/MICROSOFT/i, "W3Schools");

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Methods</h1>
<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Please visit Microsoft!</p>

<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML; 
  document.getElementById("demo").innerHTML =
  text.replace(/MICROSOFT/i,"W3Schools");
}
</script>

</body>
</html>


Note

Les expressions régulières sont écrites sans guillemets.

Pour remplacer toutes les correspondances, utilisez une expression régulière avec un indicateur /g (correspondance globale) :

Exemple

let text = "Please visit Microsoft and Microsoft!";
let newText = text.replace(/Microsoft/g, "W3Schools");

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Methods</h1>
<p>Replace all occurrences of "Microsoft" with "W3Schools" in the paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Please visit Microsoft and Microsoft!</p>

<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML; 
  document.getElementById("demo").innerHTML =
  text.replace(/Microsoft/g,"W3Schools");
}
</script>

</body>
</html>


Note

Vous en apprendrez beaucoup plus sur les expressions régulières dans le chapitre JavaScript Regular Expressions.


Chaîne JavaScript ReplaceAll()

En 2021, JavaScript a introduit la méthode de chaîne replaceAll() :

Exemple

text = text.replaceAll("Cats","Dogs");
text = text.replaceAll("cats","dogs");

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The replaceAll() Method</h2>

<p>ES2021 intoduced the string method replaceAll().</p>

<p id="demo"></p>

<script>
let text = "I love cats. Cats are very easy to love. Cats are very popular."
text = text.replaceAll("Cats","Dogs");
text = text.replaceAll("cats","dogs");

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

La méthode replaceAll() vous permet de spécifier un expression régulière au lieu d’une chaîne à remplacer.

Si le paramètre est une expression régulière, l'indicateur global (g) doit être défini, sinon une TypeError est levée.

Exemple

text = text.replaceAll(/Cats/g,"Dogs");
text = text.replaceAll(/cats/g,"dogs");

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The replaceAll() Method</h2>

<p>ES2021 intoduced the string method replaceAll().</p>

<p id="demo"></p>

<script>
let text = "I love cats. Cats are very easy to love. Cats are very popular";
text = text.replaceAll(/Cats/g,"Dogs");
text = text.replaceAll(/cats/g,"dogs");

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Note

replaceAll() est une fonctionnalité ES2021.

replaceAll() ne fonctionne pas dans Internet Explorer.


Conversion en majuscules et minuscules

Une chaîne est convertie en majuscules avec toUpperCase() :

Une chaîne est convertie en minuscules avec toLowerCase() :


Chaîne JavaScript toUpperCase()

Exemple

let text1 = "Hello World!";
let text2 = text1.toUpperCase();

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Methods</h1>
<p>Convert string to upper case:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Hello World!</p>

<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML;
  document.getElementById("demo").innerHTML =
  text.toUpperCase();
}
</script>

</body>
</html>

Chaîne JavaScript versLowerCase()

Exemple

let text1 = "Hello World!";       // String
let text2 = text1.toLowerCase();  // text2 is text1 
converted to lower

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Methods</h1>
<p>Convert string to lower case:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Hello World!</p>

<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML;
  document.getElementById("demo").innerHTML =
  text.toLowerCase();
}
</script>

</body>
</html>

Concatturation de chaîne JavaScript()

concat() joint deux chaînes ou plus :

Exemple

let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ", text2);

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String</h1>
<h2>The concat() Method</h2>

<p>The concat() method joins two or more strings:</p>

<p id="demo"></p>

<script>
let text1 = "Hello";
let text2 = "World!";
let text3 = text1.concat(" ",text2);
document.getElementById("demo").innerHTML = text3;
</script>

</body>
</html>


La méthode concat() peut être utilisée à la place de l'opérateur plus. Ces deux lignes font la même chose :

Exemple

text = "Hello" + " " + "World!";
text = "Hello".concat(" ", "World!");

Note

Toutes les méthodes de chaîne renvoient une nouvelle chaîne. Ils ne modifient pas la chaîne d'origine.

Dit formellement :

Les chaînes sont immuables : les chaînes ne peuvent pas être modifiées, seulement remplacées.


Garniture de chaîne JavaScript()

La méthode trim() supprime les espaces des deux côtés d'une chaîne :

Exemple

let text1 = "      Hello World!      ";
let text2 = text1.trim();

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The trim() Method</h2>

<p id="demo"></p>

<script>
let text1 = "     Hello World!     ";
let text2 = text1.trim();

document.getElementById("demo").innerHTML =
"Length text1 = " + text1.length + "<br>Length text2 = " + text2.length;
</script>

</body>
</html>

Chaîne JavaScript trimStart()

ECMAScript 2019 a ajouté la méthode String trimStart() à JavaScript. <p>La méthode trimStart() fonctionne comme trim(), mais supprime les espaces uniquement à partir du début de un string.

Exemple

let text1 = "     Hello World!     ";
let text2 = text1.trimStart();

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The trimStart() Method</h2>

<p id="demo"></p>

<script>
let text1 = "     Hello World!     ";
let text2 = text1.trimStart();

document.getElementById("demo").innerHTML =
"Length text1 = " + text1.length + "<br>Length text2 = " + text2.length;
</script>

</body>
</html>

La chaîne JavaScript trimStart() est prise en charge dans tous les navigateurs modernes depuis janvier 2020 :

Chrome 66 Edge 79 Firefox 61 Safari 12 Opera 50
Apr 2018 Jan 2020 Jun 2018 Sep 2018 May 2018

Chaîne JavaScript trimEnd()

ECMAScript 2019 a ajouté la méthode de chaîne trimEnd() à JavaScript. <p>La méthode trimEnd() fonctionne comme trim(), mais supprime les espaces uniquement à la fin de un string.

Exemple

let text1 = "     Hello World!     ";
let text2 = text1.trimEnd();

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The trimEnd() Method</h2>

<p id="demo"></p>

<script>
let text1 = "     Hello World!     ";
let text2 = text1.trimEnd();

document.getElementById("demo").innerHTML =
"Length text1 = " + text1.length + "<br>Length text2 = " + text2.length;
</script>

</body>
</html>

La chaîne JavaScript trimEnd() est prise en charge dans tous les navigateurs modernes depuis janvier 2020 :

Chrome 66 Edge 79 Firefox 61 Safari 12 Opera 50
Apr 2018 Jan 2020 Jun 2018 Sep 2018 May 2018

Remplissage de chaîne JavaScript

ECMAScript 2017 a ajouté deux nouvelles méthodes de chaîne à JavaScript : padStart() et padEnd() pour prendre en charge le remplissage au début et à la fin d'une chaîne.


Chaîne JavaScript padStart()

La méthode padStart() complète une chaîne depuis le début.

Il complète une chaîne avec une autre chaîne (plusieurs fois) jusqu'à ce qu'elle atteigne une longueur donnée.

Exemples

Remplissez une chaîne avec "0" jusqu'à ce qu'elle atteigne la longueur 4 :

let text = "5";
let padded = text.padStart(4,"0");

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The padStart() Method</h2>

<p>The padStart() method pads a string from the start.</p>
<p>It pads the string with another string (multiple times) until it reaches a given length.</p>

<p id="demo"></p>

<script>
let text = "5";
text = text.padStart(4,"0");

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Remplissez une chaîne avec "x" jusqu'à ce qu'elle atteigne la longueur 4 :

let text = "5";
let padded = text.padStart(4,"x");

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The padStart() Method</h2>

<p>The padStart() method pads a string from the start.</p>
<p>It pads the string with another string (multiple times) until it reaches a given length.</p>

<p id="demo"></p>

<script>
let text = "5";
document.getElementById("demo").innerHTML = text.padStart(4,"x");
</script>

</body>
</html>

Note

La méthode padStart() est une méthode de chaîne.

Pour remplir un nombre, convertissez d’abord le nombre en chaîne.

Voir l'exemple ci-dessous.

Exemple

let numb = 5;
let text = numb.toString();
let padded = text.padStart(4,"0");

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The padStart() Method</h2>

<p>The padStart() method pads a string from the start.</p>
<p>It pads the string with another string (multiple times) until it reaches a given length.</p>

<p id="demo"></p>

<script>
let numb = 5;
let text = numb.toString();
document.getElementById("demo").innerHTML = text.padStart(4,0);
</script>

</body>
</html>

Prise en charge du navigateur

padStart() est une fonctionnalité ECMAScript 2017.

Il est pris en charge dans tous les navigateurs modernes :

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

padStart() n'est pas pris en charge dans Internet Explorer.


Chaîne JavaScript padEnd()

La méthode padEnd() complète une chaîne à partir de la fin.

Il complète une chaîne avec une autre chaîne (plusieurs fois) jusqu'à ce qu'elle atteigne une longueur donnée.

Exemples

let text = "5";
let padded = text.padEnd(4,"0");

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The padEnd() Method</h2>

<p>The padEnd() method pads a string at the end.</p>
<p>It pads the string with another string (multiple times) until it reaches a given length.</p>

<p id="demo"></p>

<script>
let text = "5";
text = text.padEnd(4,"0");

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>
let text = "5";
let padded = text.padEnd(4,"x");

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The padEnd() Method</h2>

<p>The padEnd() method pads a string at the end.</p>
<p>It pads the string with another string (multiple times) until it reaches a given length.</p>

<p id="demo"></p>

<script>
let text = "5";
document.getElementById("demo").innerHTML = text.padEnd(4,"x");
</script>

</body>
</html>

Note

La méthode padEnd() est une méthode de chaîne.

Pour remplir un nombre, convertissez d’abord le nombre en chaîne.

Voir l'exemple ci-dessous.

Exemple

let numb = 5;
let text = numb.toString();
let padded = text.padEnd(4,"0");

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The padEnd() Method</h2>

<p>The padEnd() method pads a string at the end.</p>
<p>It pads the string with another string (multiple times) until it reaches a given length.</p>

<p id="demo"></p>

<script>
let numb = 5;
let text = numb.toString();
document.getElementById("demo").innerHTML = text.padEnd(4,"x");
</script>

</body>
</html>

Prise en charge du navigateur

padEnd() est une fonctionnalité ECMAScript 2017.

Il est pris en charge dans tous les navigateurs modernes :

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

padEnd() n'est pas pris en charge dans Internet Explorer.


Extraction de caractères de chaîne

Il existe 3 méthodes pour extraire les caractères d'une chaîne :

  • charAt(position)

  • charCodeAt(position)

  • Accès à la propriété [ ]


Chaîne JavaScript charAt()

La méthode charAt() renvoie le caractère à une heure spécifiée index (position) dans une chaîne :

Exemple

let text = "HELLO WORLD";
let char = text.charAt(0);

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String</h1>
<h2>The charAt() Method</h2>

<p>The charAt() method returns the character at a given position in a string:</p>

<p id="demo"></p>

<script>
var text = "HELLO WORLD";
document.getElementById("demo").innerHTML = text.charAt(0);
</script>

</body>
</html>


Chaîne JavaScript charCodeAt()

La méthode charCodeAt() renvoie l'unicode du caractère à un index spécifié dans une chaîne :

La méthode renvoie un code UTF-16 (un entier compris entre 0 et 65535).

Exemple

let text = "HELLO WORLD";
let char = text.charCodeAt(0);

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String</h1>
<h2>The charCodeAt() Method</h2>

<p>The charCodeAt() method returns the unicode of the character at a given position in a string:</p>

<p id="demo"></p>

<script>
let text = "HELLO WORLD";
document.getElementById("demo").innerHTML = text.charCodeAt(0);
</script>

</body>
</html>


Accès à la propriété

ECMAScript 5 (2009) autorise l'accès aux propriétés [ ] sur les chaînes :

Exemple

let text = "HELLO WORLD";
let char = text[0];

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<p>Property access on strings:</p>

<p>The first character in the string is:</p>
<p id="demo"></p>

<script>
let text = "HELLO WORLD";
document.getElementById("demo").innerHTML = text[0];
</script>
</body>
</html>

Note

L'accès à la propriété peut être un peu imprévisible :

  • Cela fait ressembler les chaînes à des tableaux (mais ce n’est pas le cas)

  • Si aucun caractère n'est trouvé, [ ] renvoie undefined, tandis que charAt() renvoie une chaîne vide.

  • Il est en lecture seule. str[0]="A" ne donne aucune erreur (mais ne fonctionne pas !)

Exemple

let text = "HELLO WORLD";
text[0] = "A";    // Gives no error, but does not work

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<p>Property acces on strings are read only:</p>

<p id="demo"></p>

<script>
let text = "HELLO WORLD";

text[0] = "A";  // Does not work

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Conversion d'une chaîne en tableau

Si vous souhaitez travailler avec une chaîne sous forme de tableau, vous pouvez la convertir en tableau.

Séparation de chaîne JavaScript()

Une chaîne peut être convertie en tableau avec la méthode split() :

Exemple

text.split(",")    // Split on commas
text.split(" ")    // Split on spaces
text.split("|")    // Split on pipe

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Methods</h1>
<p>Display the first array element, after a string split:</p>

<p id="demo"></p>

<script>
let text = "a,b,c,d,e,f";
const myArray = text.split(",");
document.getElementById("demo").innerHTML = myArray[0];
</script>

</body>
</html>


Si le séparateur est omis, le tableau renvoyé contiendra la chaîne entière dans l'indice [0].

Si le séparateur est "", le tableau renvoyé sera un tableau de simples personnages:

Exemple

text.split("")

Essayez-le vous-même →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Methods</h1>
<h2>The split().Method</h2>

<p id="demo"></p>

<script>
let text = "Hello";
const myArr = text.split("");

text = "";
for (let i = 0; i < myArr.length; i++) {
  text += myArr[i] + "<br>"
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>


Référence de chaîne complète

Pour une référence complète sur String, accédez à notre :

Référence complète des chaînes JavaScript.

La référence contient des descriptions et des exemples de toutes les propriétés et méthodes de chaîne.