17
Strings & Regex
Manipulation de texte et expressions régulières
Les chaînes de caractères sont l'un des types les plus utilisés en JavaScript. Maîtriser leurs méthodes et les regex est essentiel pour manipuler du texte efficacement.
📝 Méthodes de String
const str = " Hello World ";
// NETTOYAGE
str.trim(); // "Hello World" (supprime espaces début/fin)
str.trimStart(); // "Hello World "
str.trimEnd(); // " Hello World"
// RECHERCHE
str.includes("World"); // true
str.startsWith(" He"); // true
str.endsWith("ld "); // true
str.indexOf("World"); // 8 (position, -1 si absent)
str.lastIndexOf("o"); // 10 (dernière occurrence)
// EXTRACTION
str.slice(2, 7); // "Hello" (début, fin)
str.substring(2, 7); // "Hello" (similaire, mais gère mal les négatifs)
str.substr(2, 5); // "Hello" (début, longueur) ⚠️ Déprécié
// TRANSFORMATION
str.toLowerCase(); // " hello world "
str.toUpperCase(); // " HELLO WORLD "
str.replace("World", "JS"); // " Hello JS " (1ère occurrence)
str.replaceAll("o", "0"); // " Hell0 W0rld " (toutes)
// SPLIT & JOIN
"a,b,c".split(","); // ["a", "b", "c"]
["a", "b", "c"].join("-"); // "a-b-c"
// PADDING
"5".padStart(3, "0"); // "005"
"5".padEnd(3, "0"); // "500"
// REPEAT
"Ha".repeat(3); // "HaHaHa"
🔍 Vérifier présence
str.includes("text")
str.startsWith("pre")
str.endsWith("fix")
Retournent true/false
✂️ Extraire
str.slice(start, end)
str.substring(start, end)
str.charAt(index)
Retournent une sous-chaîne
🔄 Transformer
str.toLowerCase()
str.toUpperCase()
str.replace(old, new)
Retournent une nouvelle string
➕ Construire
str.concat(str2)
str.repeat(n)
str.padStart(len, char)
Créent de nouvelles strings
🎯 Template Literals (Backticks)
const name = "Alice";
const age = 25;
// INTERPOLATION
const message = `Hello ${name}, you are ${age} years old`;
// "Hello Alice, you are 25 years old"
// EXPRESSIONS
const result = `2 + 2 = ${2 + 2}`; // "2 + 2 = 4"
const upper = `Name: ${name.toUpperCase()}`; // "Name: ALICE"
// MULTILIGNE (sans \n)
const html = `
${name}
Age: ${age}
`;
// TAGGED TEMPLATES (avancé)
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
return result + str + (values[i] ? `${values[i]}` : '');
}, '');
}
const tagged = highlight`Name: ${name}, Age: ${age}`;
// "Name: Alice, Age: 25"
🔎 Expressions Régulières (Regex)
// CRÉATION
const regex1 = /pattern/flags;
const regex2 = new RegExp('pattern', 'flags');
// FLAGS
// g = global (toutes les occurrences)
// i = insensitive (ignore la casse)
// m = multiline (^ et $ pour chaque ligne)
// MÉTHODES
const text = "Hello World, hello universe";
// test() - Retourne true/false
/hello/i.test(text); // true (ignore casse avec 'i')
// match() - Retourne les correspondances
text.match(/hello/gi); // ["Hello", "hello"]
// matchAll() - Itérateur de toutes les correspondances
[...text.matchAll(/h(\w+)/gi)]; // Détails complets
// replace() avec regex
text.replace(/hello/gi, "Hi"); // "Hi World, Hi universe"
// split() avec regex
"a1b2c3".split(/\d/); // ["a", "b", "c"]
// search() - Position de la 1ère correspondance
text.search(/world/i); // 6
📋 Patterns Regex Courants
| Pattern | Description | Exemple |
|---|---|---|
\d |
Chiffre (0-9) | /\d+/ → "123" |
\w |
Mot (a-z, A-Z, 0-9, _) | /\w+/ → "hello" |
\s |
Espace blanc | /\s+/ → " " |
. |
N'importe quel caractère | /h.t/ → "hat", "hot" |
^ |
Début de chaîne | /^Hello/ → "Hello..." |
$ |
Fin de chaîne | /world$/ → "...world" |
+ |
1 ou plus | /a+/ → "a", "aaa" |
* |
0 ou plus | /a*/ → "", "aaa" |
? |
0 ou 1 | /colou?r/ → "color", "colour" |
[abc] |
a ou b ou c | /[aeiou]/ → voyelles |
[^abc] |
Pas a, b ou c | /[^0-9]/ → non-chiffre |
(x|y) |
x ou y | /(cat|dog)/ → "cat" ou "dog" |
🎮 Testeur de Regex
Testez vos expressions régulières en temps réel.
Entrez un pattern et cliquez sur Tester
💼 Cas d'Usage Pratiques
// VALIDATION EMAIL
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
emailRegex.test("user@example.com"); // true
// VALIDATION TÉLÉPHONE (FR)
const phoneRegex = /^0[1-9](\d{2}){4}$/;
phoneRegex.test("0612345678"); // true
// EXTRAIRE TOUS LES NOMBRES
const text = "Prix: 19.99€, Quantité: 5";
text.match(/\d+\.?\d*/g); // ["19.99", "5"]
// NETTOYER UN SLUG
function slugify(text) {
return text
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, '') // Retire caractères spéciaux
.replace(/\s+/g, '-') // Espaces → tirets
.replace(/-+/g, '-'); // Tirets multiples → 1 seul
}
slugify("Hello World!"); // "hello-world"
// MASQUER UN NUMÉRO DE CARTE
const card = "1234 5678 9012 3456";
card.replace(/\d(?=\d{4})/g, "*"); // "**** **** **** 3456"
// CAPITALISER CHAQUE MOT
function capitalize(str) {
return str.replace(/\b\w/g, char => char.toUpperCase());
}
capitalize("hello world"); // "Hello World"
Best Practice : Utilisez les template literals pour la concaténation. Préférez
includes() à indexOf() !== -1. Testez vos regex sur regex101.com. Échappez
les caractères spéciaux avec \.
⚠️ Pièges : Les strings sont immutables (toutes les méthodes retournent une nouvelle
string).
replace() sans flag g ne remplace que la 1ère occurrence. Les regex
peuvent être lentes sur de gros textes (attention aux catastrophic backtracking).