From d413f210b77ed126759c5fab06ddfeab3ccbfd96 Mon Sep 17 00:00:00 2001 From: "Queen Vinyl Da.i'gyu-Kazotetsu" Date: Fri, 28 Jul 2023 01:47:09 -0700 Subject: [PATCH] fr: Format /web/javascript using Prettier (part 8) (#14647) --- .../proxy/proxy/ownkeys/index.md | 28 +++-- .../proxy/proxy/preventextensions/index.md | 35 +++--- .../global_objects/proxy/proxy/set/index.md | 32 ++--- .../proxy/proxy/setprototypeof/index.md | 21 ++-- .../global_objects/proxy/revocable/index.md | 19 +-- .../global_objects/rangeerror/index.md | 28 +++-- .../rangeerror/rangeerror/index.md | 24 ++-- .../global_objects/referenceerror/index.md | 26 ++-- .../referenceerror/referenceerror/index.md | 38 +++--- .../global_objects/reflect/apply/index.md | 2 +- .../global_objects/reflect/construct/index.md | 8 +- .../reflect/defineproperty/index.md | 4 +- .../reflect/deleteproperty/index.md | 4 +- .../global_objects/reflect/get/index.md | 6 +- .../reflect/getownpropertydescriptor/index.md | 6 +- .../reflect/getprototypeof/index.md | 14 +-- .../global_objects/reflect/has/index.md | 21 ++-- .../reflect/isextensible/index.md | 2 +- .../global_objects/reflect/ownkeys/index.md | 16 ++- .../reflect/preventextensions/index.md | 2 +- .../reflect/setprototypeof/index.md | 2 +- .../global_objects/regexp/@@match/index.md | 16 +-- .../global_objects/regexp/@@matchall/index.md | 14 +-- .../global_objects/regexp/@@replace/index.md | 16 +-- .../global_objects/regexp/@@search/index.md | 16 +-- .../global_objects/regexp/@@species/index.md | 6 +- .../global_objects/regexp/@@split/index.md | 14 +-- .../global_objects/regexp/compile/index.md | 2 +- .../global_objects/regexp/exec/index.md | 14 +-- .../global_objects/regexp/flags/index.md | 10 +- .../global_objects/regexp/global/index.md | 12 +- .../global_objects/regexp/hasindices/index.md | 8 +- .../reference/global_objects/regexp/index.md | 33 ++--- .../global_objects/regexp/input/index.md | 12 +- .../global_objects/regexp/lastindex/index.md | 6 +- .../global_objects/regexp/lastmatch/index.md | 6 +- .../global_objects/regexp/lastparen/index.md | 6 +- .../regexp/leftcontext/index.md | 8 +- .../global_objects/regexp/n/index.md | 22 ++-- .../global_objects/regexp/regexp/index.md | 6 +- .../regexp/rightcontext/index.md | 6 +- .../global_objects/regexp/source/index.md | 6 +- .../global_objects/regexp/sticky/index.md | 2 +- .../global_objects/regexp/test/index.md | 20 +-- .../global_objects/regexp/tostring/index.md | 8 +- .../global_objects/regexp/unicode/index.md | 2 +- .../global_objects/set/@@iterator/index.md | 4 +- .../global_objects/set/@@species/index.md | 2 +- .../global_objects/set/clear/index.md | 6 +- .../global_objects/set/delete/index.md | 10 +- .../global_objects/set/entries/index.md | 2 +- .../global_objects/set/foreach/index.md | 2 +- .../reference/global_objects/set/has/index.md | 12 +- .../reference/global_objects/set/index.md | 59 +++++---- .../reference/global_objects/set/set/index.md | 16 +-- .../global_objects/set/size/index.md | 2 +- .../sharedarraybuffer/bytelength/index.md | 2 +- .../global_objects/sharedarraybuffer/index.md | 12 +- .../sharedarraybuffer/index.md | 4 +- .../sharedarraybuffer/slice/index.md | 14 +-- .../global_objects/string/@@iterator/index.md | 2 +- .../global_objects/string/anchor/index.md | 8 +- .../global_objects/string/at/index.md | 8 +- .../global_objects/string/big/index.md | 10 +- .../global_objects/string/blink/index.md | 2 +- .../global_objects/string/bold/index.md | 10 +- .../global_objects/string/charat/index.md | 63 +++++----- .../global_objects/string/charcodeat/index.md | 115 +++++++++--------- .../string/codepointat/index.md | 44 ++++--- .../global_objects/string/concat/index.md | 6 +- .../global_objects/string/endswith/index.md | 15 ++- .../global_objects/string/fixed/index.md | 2 +- .../global_objects/string/fontcolor/index.md | 13 +- .../global_objects/string/fontsize/index.md | 4 +- .../string/fromcharcode/index.md | 14 +-- .../string/fromcodepoint/index.md | 30 ++--- .../global_objects/string/includes/index.md | 24 ++-- .../reference/global_objects/string/index.md | 33 ++--- .../global_objects/string/indexof/index.md | 33 ++--- .../global_objects/string/italics/index.md | 2 +- .../string/lastindexof/index.md | 28 ++--- .../global_objects/string/length/index.md | 2 +- .../global_objects/string/link/index.md | 2 +- .../string/localecompare/index.md | 27 ++-- .../global_objects/string/match/index.md | 16 +-- .../global_objects/string/matchall/index.md | 18 +-- .../global_objects/string/normalize/index.md | 4 - .../global_objects/string/padend/index.md | 8 +- .../global_objects/string/padstart/index.md | 10 +- .../global_objects/string/raw/index.md | 8 +- .../global_objects/string/repeat/index.md | 23 ++-- .../global_objects/string/replace/index.md | 37 +++--- .../global_objects/string/replaceall/index.md | 6 +- .../global_objects/string/search/index.md | 2 +- .../global_objects/string/slice/index.md | 16 +-- .../global_objects/string/small/index.md | 8 +- .../global_objects/string/split/index.md | 23 ++-- .../global_objects/string/startswith/index.md | 4 +- .../global_objects/string/strike/index.md | 2 +- .../global_objects/string/string/index.md | 8 +- 100 files changed, 757 insertions(+), 689 deletions(-) diff --git a/files/fr/web/javascript/reference/global_objects/proxy/proxy/ownkeys/index.md b/files/fr/web/javascript/reference/global_objects/proxy/proxy/ownkeys/index.md index ce72b0624d1ac5..bcfa2e5f493206 100644 --- a/files/fr/web/javascript/reference/global_objects/proxy/proxy/ownkeys/index.md +++ b/files/fr/web/javascript/reference/global_objects/proxy/proxy/ownkeys/index.md @@ -14,8 +14,7 @@ La méthode **`handler.ownKeys()`** est une trappe pour {{jsxref("Object.getOwnP ```js var p = new Proxy(cible, { - ownKeys: function(cible) { - } + ownKeys: function (cible) {}, }); ``` @@ -57,15 +56,18 @@ Si les invariants suivants ne sont pas respectés, le proxy renverra une excepti Dans l'exemple suivant, on intercepte l'action de {{jsxref("Object.getOwnPropertyNames()")}}. ```js -var p = new Proxy({}, { - ownKeys: function(target) { - console.log("appelée"); - return ["a", "b", "c"]; - } -}); +var p = new Proxy( + {}, + { + ownKeys: function (target) { + console.log("appelée"); + return ["a", "b", "c"]; + }, + }, +); console.log(Object.getOwnPropertyNames(p)); // "appelée" - // [ "a", "b", "c"] +// [ "a", "b", "c"] ``` L'exemple suivant ne respecte pas l'ensemble des invariants : @@ -75,13 +77,13 @@ var obj = {}; Object.defineProperty(obj, "a", { configurable: false, enumerable: true, - value: 10 } -); + value: 10, +}); var p = new Proxy(obj, { - ownKeys: function(cible) { + ownKeys: function (cible) { return [123, 12.5, true, false, undefined, null, {}, []]; - } + }, }); console.log(Object.getOwnPropertyNames(p)); diff --git a/files/fr/web/javascript/reference/global_objects/proxy/proxy/preventextensions/index.md b/files/fr/web/javascript/reference/global_objects/proxy/proxy/preventextensions/index.md index d8a53c4114e13c..bcfaaf77f936e1 100644 --- a/files/fr/web/javascript/reference/global_objects/proxy/proxy/preventextensions/index.md +++ b/files/fr/web/javascript/reference/global_objects/proxy/proxy/preventextensions/index.md @@ -14,8 +14,7 @@ La méthode **`handler.preventExtensions()`** est une trappe pour {{jsxref("Obje ```js var p = new Proxy(cible, { - preventExtensions: function(cible) { - } + preventExtensions: function (cible) {}, }); ``` @@ -52,26 +51,32 @@ Si les invariants suivants ne sont pas respectés, le proxy renverra une execpti On intercepte l'appel à {{jsxref("Object.preventExtensions()")}} dans l'exemple suivant : ```js -var p = new Proxy({}, { - preventExtensions: function(cible) { - console.log("appelé"); - Object.preventExtensions(cible); - return true; - } -}); +var p = new Proxy( + {}, + { + preventExtensions: function (cible) { + console.log("appelé"); + Object.preventExtensions(cible); + return true; + }, + }, +); console.log(Object.preventExtensions(p)); // "appelé" - // true +// true ``` Le code suivant ne respecte pas l'invariant : ```js -var p = new Proxy({}, { - preventExtensions: function(cible) { - return true; - } -}); +var p = new Proxy( + {}, + { + preventExtensions: function (cible) { + return true; + }, + }, +); Object.preventExtensions(p); // TypeError est levée ``` diff --git a/files/fr/web/javascript/reference/global_objects/proxy/proxy/set/index.md b/files/fr/web/javascript/reference/global_objects/proxy/proxy/set/index.md index 60c45da9185f2b..5a56143bd313e2 100644 --- a/files/fr/web/javascript/reference/global_objects/proxy/proxy/set/index.md +++ b/files/fr/web/javascript/reference/global_objects/proxy/proxy/set/index.md @@ -14,8 +14,7 @@ La méthode **`handler.set()`** est une trappe permettant d'intercepter les opé ```js var p = new Proxy(cible, { - set: function(cible, propriété, valeur, récepteur) { - } + set: function (cible, propriété, valeur, récepteur) {}, }); ``` @@ -61,19 +60,22 @@ Si les invariants suivants ne sont pas respectés, le proxy renverra une excepti Dans l'exemple qui suit, on intercepte la définition d'une nouvelle propriété. ```js -var p = new Proxy({}, { - set: function(target, prop, value, receiver) { - target[prop] = value; - console.log('property set: ' + prop + ' = ' + value); - return true; - } -}); - -console.log('a' in p); // false - -p.a = 10; // "property set: a = 10" -console.log('a' in p); // true -console.log(p.a); // 10 +var p = new Proxy( + {}, + { + set: function (target, prop, value, receiver) { + target[prop] = value; + console.log("property set: " + prop + " = " + value); + return true; + }, + }, +); + +console.log("a" in p); // false + +p.a = 10; // "property set: a = 10" +console.log("a" in p); // true +console.log(p.a); // 10 ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/proxy/proxy/setprototypeof/index.md b/files/fr/web/javascript/reference/global_objects/proxy/proxy/setprototypeof/index.md index 4cc684bf3c96c0..c136ca3ec05cf7 100644 --- a/files/fr/web/javascript/reference/global_objects/proxy/proxy/setprototypeof/index.md +++ b/files/fr/web/javascript/reference/global_objects/proxy/proxy/setprototypeof/index.md @@ -14,8 +14,7 @@ La méthode **`handler.setPrototypeOf()`** est une trappe pour intercepter {{jsx ```js var p = new Proxy(cible, { - setPrototypeOf: function(cible, prototype) { - } + setPrototypeOf: function (cible, prototype) {}, }); ``` @@ -57,12 +56,13 @@ Avec cette première approche, toute opération qui voudra modifier le prototype ```js var handlerReturnsFalse = { - setPrototypeOf(target, newProto) { - return false; - } + setPrototypeOf(target, newProto) { + return false; + }, }; -var newProto = {}, target = {}; +var newProto = {}, + target = {}; var p1 = new Proxy(target, handlerReturnsFalse); Object.setPrototypeOf(p1, newProto); @@ -75,12 +75,13 @@ Avec cette seconde approche, toute tentative de modification génèrera une exce ```js var handlerThrows = { - setPrototypeOf(target, newProto) { - throw new Error("erreur custom"); - } + setPrototypeOf(target, newProto) { + throw new Error("erreur custom"); + }, }; -var newProto = {}, target = {}; +var newProto = {}, + target = {}; var p2 = new Proxy(target, handlerThrows); Object.setPrototypeOf(p2, newProto); diff --git a/files/fr/web/javascript/reference/global_objects/proxy/revocable/index.md b/files/fr/web/javascript/reference/global_objects/proxy/revocable/index.md index d8b05d631379a1..ab177505ad9e70 100644 --- a/files/fr/web/javascript/reference/global_objects/proxy/revocable/index.md +++ b/files/fr/web/javascript/reference/global_objects/proxy/revocable/index.md @@ -41,20 +41,23 @@ Si la fonction `revoke()` est appelée, le proxy devient inutilisable et toutes ### Utiliser `Proxy.revocable()` ```js -let revocable = Proxy.revocable({}, { - get: function(cible, nom) { - return "[[" + nom + "]]"; - } -}); +let revocable = Proxy.revocable( + {}, + { + get: function (cible, nom) { + return "[[" + nom + "]]"; + }, + }, +); let proxy = revocable.proxy; console.log(proxy.toto); // "[[toto]]" revocable.revoke(); console.log(proxy.toto); // TypeError est levée -proxy.toto = 1; // TypeError à nouveau -delete proxy.toto; // TypeError toujours -typeof proxy; // "object", typeof ne déclenche aucune trappe +proxy.toto = 1; // TypeError à nouveau +delete proxy.toto; // TypeError toujours +typeof proxy; // "object", typeof ne déclenche aucune trappe ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/rangeerror/index.md b/files/fr/web/javascript/reference/global_objects/rangeerror/index.md index 54a53dee87e5b3..118b53ec197faf 100644 --- a/files/fr/web/javascript/reference/global_objects/rangeerror/index.md +++ b/files/fr/web/javascript/reference/global_objects/rangeerror/index.md @@ -45,17 +45,18 @@ Par exemple, cela peut être le cas quand : ```js const MIN = 200; const MAX = 300; -function verifier( num ) { - if( num < MIN || num > MAX ) { - throw new RangeError( "Le paramètre doit être compris entre " + MIN + " et " + MAX ); +function verifier(num) { + if (num < MIN || num > MAX) { + throw new RangeError( + "Le paramètre doit être compris entre " + MIN + " et " + MAX, + ); } -}; +} try { verifier(500); -} -catch (e) { - if (e instanceof RangeError ){ +} catch (e) { + if (e instanceof RangeError) { // On gère ce qui se passe en cas d'erreur } } @@ -64,17 +65,18 @@ catch (e) { ### Utiliser `RangeError` avec des valeurs non-numériques ```js -function verifier(valeur){ - if(["pomme", "banane", "carotte"].includes(valeur) === false){ - throw new RangeError("L'argument n'est pas un fruit parmi pomme / banane ou carotte."); +function verifier(valeur) { + if (["pomme", "banane", "carotte"].includes(valeur) === false) { + throw new RangeError( + "L'argument n'est pas un fruit parmi pomme / banane ou carotte.", + ); } } try { verifier("chou"); -} -catch(erreur) { - if(erreur instanceof RangeError){ +} catch (erreur) { + if (erreur instanceof RangeError) { //On gère ce qui se passe en cas d'erreur } } diff --git a/files/fr/web/javascript/reference/global_objects/rangeerror/rangeerror/index.md b/files/fr/web/javascript/reference/global_objects/rangeerror/rangeerror/index.md index facf916ebba1da..5238ffd60188a9 100644 --- a/files/fr/web/javascript/reference/global_objects/rangeerror/rangeerror/index.md +++ b/files/fr/web/javascript/reference/global_objects/rangeerror/rangeerror/index.md @@ -11,10 +11,10 @@ Le constructeur **`RangeError()`** permet de créer une erreur lorsqu'une valeur ## Syntaxe ```js -new RangeError() -new RangeError(message) -new RangeError(message, nomFichier) -new RangeError(message, nomFichier, numeroLigne) +new RangeError(); +new RangeError(message); +new RangeError(message, nomFichier); +new RangeError(message, nomFichier, numeroLigne); ``` ### Parameters @@ -32,15 +32,14 @@ new RangeError(message, nomFichier, numeroLigne) ```js function verifier(n) { - if( !(n >= -500 && n <= 500) ) { + if (!(n >= -500 && n <= 500)) { throw new RangeError("L'argument doit être compris entre -500 et 500."); } } try { verifier(2000); -} -catch(error) { +} catch (error) { if (error instanceof RangeError) { // Gérer l'erreur } @@ -51,16 +50,17 @@ catch(error) { ```js function verifier(valeur) { - if(["pomme", "banane", "carotte"].includes(valeur) === false) { - throw new RangeError("L'argument doit valeur 'pomme', 'banane', ou 'carotte'."); + if (["pomme", "banane", "carotte"].includes(valeur) === false) { + throw new RangeError( + "L'argument doit valeur 'pomme', 'banane', ou 'carotte'.", + ); } } try { verifier("chou"); -} -catch(error) { - if(error instanceof RangeError) { +} catch (error) { + if (error instanceof RangeError) { // Gérer l'erreur } } diff --git a/files/fr/web/javascript/reference/global_objects/referenceerror/index.md b/files/fr/web/javascript/reference/global_objects/referenceerror/index.md index 0dd5d8f6dec7f2..41d262c280f6c1 100644 --- a/files/fr/web/javascript/reference/global_objects/referenceerror/index.md +++ b/files/fr/web/javascript/reference/global_objects/referenceerror/index.md @@ -37,12 +37,12 @@ try { let a = variableNonDefinie; } catch (e) { console.log(e instanceof ReferenceError); // true - console.log(e.message); // "variableNonDefinie is not defined" - console.log(e.name); // "ReferenceError" - console.log(e.fileName); // "Scratchpad/1" - console.log(e.lineNumber); // 2 - console.log(e.columnNumber); // 6 - console.log(e.stack); // "@Scratchpad/2:2:7\n" + console.log(e.message); // "variableNonDefinie is not defined" + console.log(e.name); // "ReferenceError" + console.log(e.fileName); // "Scratchpad/1" + console.log(e.lineNumber); // 2 + console.log(e.columnNumber); // 6 + console.log(e.stack); // "@Scratchpad/2:2:7\n" } ``` @@ -50,15 +50,15 @@ try { ```js try { - throw new ReferenceError('Bonjour', 'unFichier.js', 10); + throw new ReferenceError("Bonjour", "unFichier.js", 10); } catch (e) { console.log(e instanceof ReferenceError); // true - console.log(e.message); // "Bonjour" - console.log(e.name); // "ReferenceError" - console.log(e.fileName); // "unFichier.js" - console.log(e.lineNumber); // 10 - console.log(e.columnNumber); // 0 - console.log(e.stack); // "@Scratchpad/2:2:9\n" + console.log(e.message); // "Bonjour" + console.log(e.name); // "ReferenceError" + console.log(e.fileName); // "unFichier.js" + console.log(e.lineNumber); // 10 + console.log(e.columnNumber); // 0 + console.log(e.stack); // "@Scratchpad/2:2:9\n" } ``` diff --git a/files/fr/web/javascript/reference/global_objects/referenceerror/referenceerror/index.md b/files/fr/web/javascript/reference/global_objects/referenceerror/referenceerror/index.md index c984d76f5214a4..013b0b554eb9f5 100644 --- a/files/fr/web/javascript/reference/global_objects/referenceerror/referenceerror/index.md +++ b/files/fr/web/javascript/reference/global_objects/referenceerror/referenceerror/index.md @@ -11,10 +11,10 @@ Le constructeur **`ReferenceError()`** permet de créer des objets représentant ## Syntaxe ```js -new ReferenceError() -new ReferenceError(message) -new ReferenceError(message, nomFichier) -new ReferenceError(message, nomFichier, numeroLigne) +new ReferenceError(); +new ReferenceError(message); +new ReferenceError(message, nomFichier); +new ReferenceError(message, nomFichier, numeroLigne); ``` ### Paramètres @@ -34,13 +34,13 @@ new ReferenceError(message, nomFichier, numeroLigne) try { let a = variableIndefinie; } catch (e) { - console.log(e instanceof ReferenceError); // true - console.log(e.message); // "variableIndefinie is not defined" - console.log(e.name); // "ReferenceError" - console.log(e.fileName); // "Scratchpad/1" - console.log(e.lineNumber); // 2 - console.log(e.columnNumber); // 6 - console.log(e.stack); // "@Scratchpad/2:2:7\n" + console.log(e instanceof ReferenceError); // true + console.log(e.message); // "variableIndefinie is not defined" + console.log(e.name); // "ReferenceError" + console.log(e.fileName); // "Scratchpad/1" + console.log(e.lineNumber); // 2 + console.log(e.columnNumber); // 6 + console.log(e.stack); // "@Scratchpad/2:2:7\n" } ``` @@ -48,15 +48,15 @@ try { ```js try { - throw new ReferenceError('Coucou', 'unFichier.js', 10); + throw new ReferenceError("Coucou", "unFichier.js", 10); } catch (e) { - console.log(e instanceof ReferenceError); // true - console.log(e.message); // "Coucou" - console.log(e.name); // "ReferenceError" - console.log(e.fileName); // "unFichier.js" - console.log(e.lineNumber); // 10 - console.log(e.columnNumber); // 0 - console.log(e.stack); // "@Scratchpad/2:2:9\n" + console.log(e instanceof ReferenceError); // true + console.log(e.message); // "Coucou" + console.log(e.name); // "ReferenceError" + console.log(e.fileName); // "unFichier.js" + console.log(e.lineNumber); // 10 + console.log(e.columnNumber); // 0 + console.log(e.stack); // "@Scratchpad/2:2:9\n" } ``` diff --git a/files/fr/web/javascript/reference/global_objects/reflect/apply/index.md b/files/fr/web/javascript/reference/global_objects/reflect/apply/index.md index c31e1d9ad4fbc2..69b75be8f7cb80 100644 --- a/files/fr/web/javascript/reference/global_objects/reflect/apply/index.md +++ b/files/fr/web/javascript/reference/global_objects/reflect/apply/index.md @@ -13,7 +13,7 @@ La méthode statique **`Reflect.apply()`** permet d'appeler une fonction cible a ## Syntaxe ```js -Reflect.apply(cible, argumentThis, listeArguments) +Reflect.apply(cible, argumentThis, listeArguments); ``` ### Paramètres diff --git a/files/fr/web/javascript/reference/global_objects/reflect/construct/index.md b/files/fr/web/javascript/reference/global_objects/reflect/construct/index.md index 68f5b68cd9e73b..a5683d89dfaa55 100644 --- a/files/fr/web/javascript/reference/global_objects/reflect/construct/index.md +++ b/files/fr/web/javascript/reference/global_objects/reflect/construct/index.md @@ -70,11 +70,11 @@ Avant l'apparition de `Reflect`, on pouvait construire des objets avec une combi ```js function MaClasseA() { - this.name = 'A'; + this.name = "A"; } function MaClasseB() { - this.name = 'B'; + this.name = "B"; } // Avec cette instruction : @@ -100,11 +100,11 @@ Mais quand on appelle `Reflect.construct()`, `new.target` pointe vers la valeur ```js function MaClasseA() { - console.log('MaClasseA'); + console.log("MaClasseA"); console.log(new.target); } function MaClasseB() { - console.log('MaClasseB'); + console.log("MaClasseB"); console.log(new.target); } diff --git a/files/fr/web/javascript/reference/global_objects/reflect/defineproperty/index.md b/files/fr/web/javascript/reference/global_objects/reflect/defineproperty/index.md index e5e862b0d54c67..d92fc5d29658a3 100644 --- a/files/fr/web/javascript/reference/global_objects/reflect/defineproperty/index.md +++ b/files/fr/web/javascript/reference/global_objects/reflect/defineproperty/index.md @@ -13,7 +13,7 @@ La méthode statique **`Reflect.defineProperty()`** est semblable à {{jsxref("O ## Syntaxe ```js -Reflect.defineProperty(cible, cléPropriété, attributs) +Reflect.defineProperty(cible, cléPropriété, attributs); ``` ### Paramètres @@ -43,7 +43,7 @@ La méthode `Reflect.defineProperty` permet d'ajouter ou de modifier finement un ```js var obj = {}; -Reflect.defineProperty(obj, "x", {value: 7}); // true +Reflect.defineProperty(obj, "x", { value: 7 }); // true obj.x; // 7 ``` diff --git a/files/fr/web/javascript/reference/global_objects/reflect/deleteproperty/index.md b/files/fr/web/javascript/reference/global_objects/reflect/deleteproperty/index.md index 7a31a359acd730..cc675abd278254 100644 --- a/files/fr/web/javascript/reference/global_objects/reflect/deleteproperty/index.md +++ b/files/fr/web/javascript/reference/global_objects/reflect/deleteproperty/index.md @@ -13,7 +13,7 @@ La méthode statique **`Reflect.deleteProperty()`** permet de supprimer des prop ## Syntaxe ```js -Reflect.deleteProperty(cible, cléPropriété) +Reflect.deleteProperty(cible, cléPropriété); ``` ### Paramètres @@ -50,7 +50,7 @@ arr; // [1, 2, 3, , 5] Reflect.deleteProperty({}, "toto"); // true // Renvoie false si une propriété n'est pas configurable -Reflect.deleteProperty(Object.freeze({toto: 1}),"toto"); // false +Reflect.deleteProperty(Object.freeze({ toto: 1 }), "toto"); // false ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/reflect/get/index.md b/files/fr/web/javascript/reference/global_objects/reflect/get/index.md index 9c888c9b05401a..47d53a07fa790f 100644 --- a/files/fr/web/javascript/reference/global_objects/reflect/get/index.md +++ b/files/fr/web/javascript/reference/global_objects/reflect/get/index.md @@ -48,9 +48,11 @@ Reflect.get(obj, "x"); // 1 Reflect.get(["zero", "un"], 1); // "un" // Proxy qui intercepte get -var x = {p: 1}; +var x = { p: 1 }; var obj = new Proxy(x, { - get(t, k, r) { return k + "truc"; } + get(t, k, r) { + return k + "truc"; + }, }); Reflect.get(obj, "toto"); // "tototruc" ``` diff --git a/files/fr/web/javascript/reference/global_objects/reflect/getownpropertydescriptor/index.md b/files/fr/web/javascript/reference/global_objects/reflect/getownpropertydescriptor/index.md index 69522ae0b97923..8c31a32b34c223 100644 --- a/files/fr/web/javascript/reference/global_objects/reflect/getownpropertydescriptor/index.md +++ b/files/fr/web/javascript/reference/global_objects/reflect/getownpropertydescriptor/index.md @@ -13,7 +13,7 @@ La méthode statique **`Reflect.getOwnPropertyDescriptor()`** est similaire à { ## Syntaxe ```js -Reflect.getOwnPropertyDescriptor(cible, cléPropriété) +Reflect.getOwnPropertyDescriptor(cible, cléPropriété); ``` ### Paramètres @@ -40,10 +40,10 @@ La méthode `Reflect.getOwnPropertyDescriptor` renvoie un descripteur pour la pr ### Utiliser `Reflect.getOwnPropertyDescriptor()` ```js -Reflect.getOwnPropertyDescriptor({x: "coucou"}, "x"); +Reflect.getOwnPropertyDescriptor({ x: "coucou" }, "x"); // {value: "coucou", writable: true, enumerable: true, configurable: true} -Reflect.getOwnPropertyDescriptor({x: "coucou"}, "y"); +Reflect.getOwnPropertyDescriptor({ x: "coucou" }, "y"); // undefined Reflect.getOwnPropertyDescriptor([], "length"); diff --git a/files/fr/web/javascript/reference/global_objects/reflect/getprototypeof/index.md b/files/fr/web/javascript/reference/global_objects/reflect/getprototypeof/index.md index c254220d3d1693..f0252c6a9ad360 100644 --- a/files/fr/web/javascript/reference/global_objects/reflect/getprototypeof/index.md +++ b/files/fr/web/javascript/reference/global_objects/reflect/getprototypeof/index.md @@ -13,7 +13,7 @@ La méthode statique **`Reflect.getPrototypeOf()`** est semblable à la méthode ## Syntaxe ```js -Reflect.getPrototypeOf(cible) +Reflect.getPrototypeOf(cible); ``` ### Paramètres @@ -47,21 +47,21 @@ Reflect.getPrototypeOf(Object.create(null)); // null ```js // Résultat identiques pour les objets -Object.getPrototypeOf({}); // Object.prototype +Object.getPrototypeOf({}); // Object.prototype Reflect.getPrototypeOf({}); // Object.prototype // Exception levée avec ES5 pour les valeurs qui ne sont pas des objets -Object.getPrototypeOf('toto'); // Throws TypeError -Reflect.getPrototypeOf('toto'); // Throws TypeError +Object.getPrototypeOf("toto"); // Throws TypeError +Reflect.getPrototypeOf("toto"); // Throws TypeError // Avec ES2015 (ES6), seul Reflect lève une exception // Object convertit automatiquement les valeurs en objets -Object.getPrototypeOf('toto'); // String.prototype -Reflect.getPrototypeOf('toto'); // Throws TypeError +Object.getPrototypeOf("toto"); // String.prototype +Reflect.getPrototypeOf("toto"); // Throws TypeError // Pour obtenir le même effet qu'avec Object en ES2015, il // faut ajouter une opération de conversion explicite -Reflect.getPrototypeOf(Object('toto')); // String.prototype +Reflect.getPrototypeOf(Object("toto")); // String.prototype ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/reflect/has/index.md b/files/fr/web/javascript/reference/global_objects/reflect/has/index.md index 7336cf65c0ab63..d714862f483880 100644 --- a/files/fr/web/javascript/reference/global_objects/reflect/has/index.md +++ b/files/fr/web/javascript/reference/global_objects/reflect/has/index.md @@ -13,7 +13,7 @@ La méthode statique **`Reflect.has()`** fonctionne comme [l'opérateur `in`](/f ## Syntaxe ```js -Reflect.has(cible, cléPropriété) +Reflect.has(cible, cléPropriété); ``` ### Paramètres @@ -38,19 +38,24 @@ La méthode `Reflect.has` vous permet de vérifier si une propriété est prése ## Exemples ```js -Reflect.has({x: 0}, "x"); // true -Reflect.has({x: 0}, "y"); // false +Reflect.has({ x: 0 }, "x"); // true +Reflect.has({ x: 0 }, "y"); // false // renvoie true pour les propriétés présentes // grâce à la chaîne de prototypes -Reflect.has({x: 0}, "toString"); +Reflect.has({ x: 0 }, "toString"); // Proxy avec la méthode .has() -obj = new Proxy({}, { - has(t, k) { return k.startsWith("bou"); } -}); +obj = new Proxy( + {}, + { + has(t, k) { + return k.startsWith("bou"); + }, + }, +); Reflect.has(obj, "bouchon"); // true -Reflect.has(obj, "bonbon"); // false +Reflect.has(obj, "bonbon"); // false ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/reflect/isextensible/index.md b/files/fr/web/javascript/reference/global_objects/reflect/isextensible/index.md index 4f571e9f01f187..dcd6144cea2b1d 100644 --- a/files/fr/web/javascript/reference/global_objects/reflect/isextensible/index.md +++ b/files/fr/web/javascript/reference/global_objects/reflect/isextensible/index.md @@ -13,7 +13,7 @@ La méthode statique **`Reflect.isExtensible()`** permet de déterminer si un ob ## Syntaxe ```js -Reflect.isExtensible(cible) +Reflect.isExtensible(cible); ``` ### Paramètres diff --git a/files/fr/web/javascript/reference/global_objects/reflect/ownkeys/index.md b/files/fr/web/javascript/reference/global_objects/reflect/ownkeys/index.md index 350ccd93a4c1a1..c40a48905a3bd5 100644 --- a/files/fr/web/javascript/reference/global_objects/reflect/ownkeys/index.md +++ b/files/fr/web/javascript/reference/global_objects/reflect/ownkeys/index.md @@ -13,7 +13,7 @@ La méthode statique **`Reflect.ownKeys()`** renvoie un tableau qui contient les ## Syntaxe ```js -Reflect.ownKeys(cible) +Reflect.ownKeys(cible); ``` ### Paramètres @@ -36,13 +36,21 @@ La méthode `Reflect.ownKeys` renvoie un tableau dont les éléments sont les cl ## Exemples ```js -Reflect.ownKeys({z: 3, y: 2, x: 1}); // [ "z", "y", "x" ] +Reflect.ownKeys({ z: 3, y: 2, x: 1 }); // [ "z", "y", "x" ] Reflect.ownKeys([]); // ["length"] var sym = Symbol.for("comète"); var sym2 = Symbol.for("météore"); -var obj = {[sym]: 0, "str1": 0, "773": 0, "0": 0, - [sym2]: 0, "-1": 0, "8": 0, "seconde str": 0}; +var obj = { + [sym]: 0, + str1: 0, + 773: 0, + 0: 0, + [sym2]: 0, + "-1": 0, + 8: 0, + "seconde str": 0, +}; Reflect.ownKeys(obj); // [ "0", "8", "773", "str1", "-1", "seconde str", Symbol(comète), Symbol(météore) ] // Indices dans l'ordre numérique diff --git a/files/fr/web/javascript/reference/global_objects/reflect/preventextensions/index.md b/files/fr/web/javascript/reference/global_objects/reflect/preventextensions/index.md index 9a99418c5c6296..154ac03f0eccbc 100644 --- a/files/fr/web/javascript/reference/global_objects/reflect/preventextensions/index.md +++ b/files/fr/web/javascript/reference/global_objects/reflect/preventextensions/index.md @@ -13,7 +13,7 @@ La méthode statique **`Reflect.preventExtensions()`** permet d'empêcher d'ajou ## Syntaxe ```js -Reflect.preventExtensions(cible) +Reflect.preventExtensions(cible); ``` ### Paramètres diff --git a/files/fr/web/javascript/reference/global_objects/reflect/setprototypeof/index.md b/files/fr/web/javascript/reference/global_objects/reflect/setprototypeof/index.md index 7f53fa5012caad..9daf0249801723 100644 --- a/files/fr/web/javascript/reference/global_objects/reflect/setprototypeof/index.md +++ b/files/fr/web/javascript/reference/global_objects/reflect/setprototypeof/index.md @@ -13,7 +13,7 @@ la méthode statique **`Reflect.setPrototypeOf()`** est semblable à la méthode ## Syntaxe ```js -Reflect.setPrototypeOf(cible, prototype) +Reflect.setPrototypeOf(cible, prototype); ``` ### Paramètres diff --git a/files/fr/web/javascript/reference/global_objects/regexp/@@match/index.md b/files/fr/web/javascript/reference/global_objects/regexp/@@match/index.md index ba5d76d38155d6..7b5b6cc5d7074c 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/@@match/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/@@match/index.md @@ -13,7 +13,7 @@ La méthode **`[@@match]()`** permet de récupérer les correspondances obtenues ## Syntaxe ```js -regexp[Symbol.match](str) +regexp[Symbol.match](str); ``` ### Paramètres @@ -30,9 +30,9 @@ Un tableau ({{jsxref("Array")}}) qui contient les résultats des correspondances Cette méthode est appelée de façon interne lorsqu'on utilise {{jsxref("String.prototype.match()")}}. Ainsi, les deux exemples qui suivent sont équivalents et le second est la version interne du premier : ```js -'abc'.match(/a/); +"abc".match(/a/); -/a/[Symbol.match]('abc'); +/a/[Symbol.match]("abc"); ``` Cette méthode existe afin de permettre d'adapter le comportement de la recherche des correspondances pour les sous-classes de `RegExp`. @@ -45,9 +45,9 @@ Cette méthode peut être utilisée comme {{jsxref("String.prototype.match()")}} ```js var re = /[0-9]+/g; -var str = '2016-01-02'; +var str = "2016-01-02"; var résultat = re[Symbol.match](str); -console.log(résultat); // ["2016", "01", "02"] +console.log(résultat); // ["2016", "01", "02"] ``` ### Utilisation de `@@match` avec une sous-classe @@ -62,13 +62,13 @@ class MaRegExp extends RegExp { return { group(n) { return résultat[n]; - } + }, }; } } -var re = new MaRegExp('([0-9]+)-([0-9]+)-([0-9]+)'); -var str = '2016-01-02'; +var re = new MaRegExp("([0-9]+)-([0-9]+)-([0-9]+)"); +var str = "2016-01-02"; var résultat = str.match(re); // String.prototype.match appelle re[@@match]. console.log(résultat.group(1)); // 2016 console.log(résultat.group(2)); // 01 diff --git a/files/fr/web/javascript/reference/global_objects/regexp/@@matchall/index.md b/files/fr/web/javascript/reference/global_objects/regexp/@@matchall/index.md index e21be9c24c9c0c..a689f6e846591d 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/@@matchall/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/@@matchall/index.md @@ -13,7 +13,7 @@ La méthode **`[@@matchAll]`** renvoie l'ensemble des correspondances d'une expr ## Syntaxe ```js -regexp[Symbol.matchAll](str) +regexp[Symbol.matchAll](str); ``` ### Paramètres @@ -30,9 +30,9 @@ Un [itérateur](/fr/docs/Web/JavaScript/Guide/iterateurs_et_generateurs). Cette méthode est appelée, en interne, par le moteur JavaScript, pendant l'exécution {{jsxref("String.prototype.matchAll()")}}. Les deux lignes qui suivent renverront donc le même résultat. ```js -'abc'.matchAll(/a/); +"abc".matchAll(/a/); -/a/[Symbol.matchAll]('abc'); +/a/[Symbol.matchAll]("abc"); ``` Cette méthode existe afin de personnaliser le comportement des correspondances pour les sous-classes de `RegExp`. @@ -45,10 +45,10 @@ Cette méthode peut être utilisée de façon semblable à {{jsxref("String.prot ```js var re = /[0-9]+/g; -var str = '2016-01-02'; +var str = "2016-01-02"; var resultat = re[Symbol.matchAll](str); -console.log(Array.from(resultat, x => x[0])); +console.log(Array.from(resultat, (x) => x[0])); // ["2016", "01", "02"] ``` @@ -68,8 +68,8 @@ class MaRegExp extends RegExp { } } -var re = new MaRegExp('([0-9]+)-([0-9]+)-([0-9]+)', 'g'); -var str = '2016-01-02|2019-03-07'; +var re = new MaRegExp("([0-9]+)-([0-9]+)-([0-9]+)", "g"); +var str = "2016-01-02|2019-03-07"; var resultat = str.matchAll(re); console.log(resultat[0]); // [ "2016-01-02", "2016", "01", "02" ] console.log(resultat[1]); // [ "2019-03-07", "2019", "03", "07" ] diff --git a/files/fr/web/javascript/reference/global_objects/regexp/@@replace/index.md b/files/fr/web/javascript/reference/global_objects/regexp/@@replace/index.md index 5faaa9b52e21d6..772421c0e5d9b3 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/@@replace/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/@@replace/index.md @@ -34,9 +34,9 @@ Une nouvelle chaîne de caractères pour laquelle les correspondances (toutes ou Cette méthode est appelée de façon interne par la méthode {{jsxref("String.prototype.replace()")}} lorsque l'arugment `pattern` argument est un objet {{jsxref("RegExp")}}. Les deux lignes de code qui suivent sont équivalentes et la seconde est la version interne de la première : ```js -'abc'.replace(/a/, 'A'); +"abc".replace(/a/, "A"); -/a/[Symbol.replace]('abc', 'A'); +/a/[Symbol.replace]("abc", "A"); ``` Cette méthode existe afin de pouvoir personnaliser le comportement du remplacement pour les classes filles de `RegExp`. @@ -51,9 +51,9 @@ Cette méthode peut être utilisée comme {{jsxref("String.prototype.replace()") ```js var re = /-/g; -var str = '2016-01-01'; -var newstr = re[Symbol.replace](str, '.'); -console.log(newstr); // 2016.01.01 +var str = "2016-01-01"; +var newstr = re[Symbol.replace](str, "."); +console.log(newstr); // 2016.01.01 ``` ### Utiliser `@@replace` dans une sous-classe @@ -76,9 +76,9 @@ class MaRegExp extends RegExp { } } -var re = new MaRegExp('\\d', '', 3); -var str = '01234567'; -var newstr = str.replace(re, '#'); // String.prototype.replace appelle re[@@replace]. +var re = new MaRegExp("\\d", "", 3); +var str = "01234567"; +var newstr = str.replace(re, "#"); // String.prototype.replace appelle re[@@replace]. console.log(newstr); // ###34567 ``` diff --git a/files/fr/web/javascript/reference/global_objects/regexp/@@search/index.md b/files/fr/web/javascript/reference/global_objects/regexp/@@search/index.md index b0caf1c94d9788..607e83ab1e61e1 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/@@search/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/@@search/index.md @@ -13,7 +13,7 @@ La méthode **`[@@search]()`** recherche une correspondance entre une expression ## Syntaxe ```js -regexp[Symbol.search](str) +regexp[Symbol.search](str); ``` ### Paramètres @@ -31,9 +31,9 @@ regexp[Symbol.search](str) Cette méthode est appelée en interne lors de l'utilisation de {{jsxref("String.prototype.search()")}}. Ainsi, les deux exemples qui suivent sont équivalents et le second est la version interne du premier : ```js -'abc'.search(/a/); +"abc".search(/a/); -/a/[Symbol.search]('abc'); +/a/[Symbol.search]("abc"); ``` Cette méthode existe afin de pouvoir adapter le comportement de la recherche pour les sous-classes de `RegExp`. @@ -46,9 +46,9 @@ Cette méthode peut être utilisée comme {{jsxref("String.prototype.search()")} ```js var re = /-/g; -var str = '2016-01-02'; +var str = "2016-01-02"; var résultat = re[Symbol.search](str); -console.log(résultat); // 4 +console.log(résultat); // 4 ``` ### Utiliser `@@search` avec une sous-classe @@ -58,7 +58,7 @@ Les sous-classes de {{jsxref("RegExp")}} peuvent surcharger `[@@search]()` afin ```js class MaRegExp extends RegExp { constructor(str) { - super(str) + super(str); this.pattern = str; } [Symbol.search](str) { @@ -66,8 +66,8 @@ class MaRegExp extends RegExp { } } -var re = new MaRegExp('a+b'); -var str = 'ab a+b'; +var re = new MaRegExp("a+b"); +var str = "ab a+b"; var résultat = str.search(re); // String.prototype.search appelle re[@@search]. console.log(résultat); // 3 ``` diff --git a/files/fr/web/javascript/reference/global_objects/regexp/@@species/index.md b/files/fr/web/javascript/reference/global_objects/regexp/@@species/index.md index 3f4e6335e1149d..985c8c7dfb6bbe 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/@@species/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/@@species/index.md @@ -13,7 +13,7 @@ La propriété accesseur **`RegExp[@@species]`** renvoie le constructeur `RegExp ## Syntaxe ```js -RegExp[Symbol.species] +RegExp[Symbol.species]; ``` ## Description @@ -34,7 +34,9 @@ Pour les objets dérivés (par exemple, une classe `MaRegExp`), la valeur de `sp class MaRegExp extends RegExp { // On surcharge species pour renvoyer // le constructeur parent RegExp - static get [Symbol.species]() { return RegExp; } + static get [Symbol.species]() { + return RegExp; + } } ``` diff --git a/files/fr/web/javascript/reference/global_objects/regexp/@@split/index.md b/files/fr/web/javascript/reference/global_objects/regexp/@@split/index.md index d8fc8865b3d4e9..992d20ea61501c 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/@@split/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/@@split/index.md @@ -32,9 +32,9 @@ Un tableau ({{jsxref("Array")}}) dont les éléments sont les sous-chaînes de c Cette méthode est appelée de façon interne par la méthode {{jsxref("String.prototype.split()")}} lorsque l'argument `str` est un objet {{jsxref("RegExp")}}. Ainsi, les deux exemples qui suivent sont équivalents et le second est la version interne du premier : ```js -'a-b-c'.split(/-/); +"a-b-c".split(/-/); -/-/[Symbol.split]('a-b-c'); +/-/[Symbol.split]("a-b-c"); ``` Cette méthode existe afin de pouvoir adapter le fonctionnement de la découpe pour les sous-classes de `RegExp`. @@ -49,9 +49,9 @@ Cette méthode peut être utilisée comme {{jsxref("String.prototype.split()")}} ```js var re = /-/g; -var str = '2016-01-02'; +var str = "2016-01-02"; var résultat = re[Symbol.split](str); -console.log(résultat); // ["2016", "01", "02"] +console.log(résultat); // ["2016", "01", "02"] ``` ### Utiliser `@@split` avec une sous-classe @@ -62,12 +62,12 @@ Les sous-classes de {{jsxref("RegExp")}} peuvent surcharger `[@@split]()` afin d class MaRegExp extends RegExp { [Symbol.split](str, limit) { var résultat = RegExp.prototype[Symbol.split].call(this, str, limit); - return résultat.map(x => "(" + x + ")"); + return résultat.map((x) => "(" + x + ")"); } } -var re = new MaRegExp('-'); -var str = '2016-01-02'; +var re = new MaRegExp("-"); +var str = "2016-01-02"; var résultat = str.split(re); // String.prototype.split appelle re[@@split]. console.log(résultat); // ["(2016)", "(01)", "(02)"] ``` diff --git a/files/fr/web/javascript/reference/global_objects/regexp/compile/index.md b/files/fr/web/javascript/reference/global_objects/regexp/compile/index.md index eba924c7a18325..9b97a56e804df6 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/compile/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/compile/index.md @@ -11,7 +11,7 @@ La méthode dépréciée **`compile()`** est utilisée afin de (re)compiler une ## Syntaxe ```js -regexObj.compile(motif, flags) +regexObj.compile(motif, flags); ``` ### Paramètres diff --git a/files/fr/web/javascript/reference/global_objects/regexp/exec/index.md b/files/fr/web/javascript/reference/global_objects/regexp/exec/index.md index f91669ec8195ef..8d328f705b2b37 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/exec/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/exec/index.md @@ -17,7 +17,7 @@ Les objets représentant des expressions rationnelles gardent un état en mémoi ## Syntaxe ```js -regexObj.exec(chaîne) +regexObj.exec(chaîne); ``` ### Paramètres @@ -39,8 +39,8 @@ Si on a l'exemple suivant : // On a une correspondance si on a "quick brown" suivi par "jumps", on ignore les caractères entre // On garde en mémoire "brown" et "jumps" // On ignore la casse -var re = /quick\s(brown).+?(jumps)/ig; -var result = re.exec('The Quick Brown Fox Jumps Over The Lazy Dog'); +var re = /quick\s(brown).+?(jumps)/gi; +var result = re.exec("The Quick Brown Fox Jumps Over The Lazy Dog"); ``` Le tableau suivant montre l'état résultant suite à ce script : @@ -136,11 +136,11 @@ Par exemple, si on utilise le fragment de code suivant : ```js var maRegex = /ab*/g; -var str = 'abbcdefabh'; +var str = "abbcdefabh"; var monTableau; while ((monTableau = maRegex.exec(str)) !== null) { - var msg = 'Trouvé ' + monTableau[0] + '. '; - msg += 'Prochaine correspondance à partir de ' + maRegex.lastIndex; + var msg = "Trouvé " + monTableau[0] + ". "; + msg += "Prochaine correspondance à partir de " + maRegex.lastIndex; console.log(msg); } ``` @@ -159,7 +159,7 @@ Trouvé ab. Prochaine correspondance à partir de 9 Il est aussi possible d'utiliser `exec()` sans créer d'objet {{jsxref("RegExp")}} explicite : ```js -var matches = /(coucou \S+)/.exec('Ceci est un coucou monde !'); +var matches = /(coucou \S+)/.exec("Ceci est un coucou monde !"); console.log(matches[1]); ``` diff --git a/files/fr/web/javascript/reference/global_objects/regexp/flags/index.md b/files/fr/web/javascript/reference/global_objects/regexp/flags/index.md index d596ac725258a7..da587d968fadc0 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/flags/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/flags/index.md @@ -19,19 +19,19 @@ Les drapeaux de la propriété `flags` sont rangés par ordre alphabétique de g ### Utiliser `flags` ```js -/toto/ig.flags; // "gi" -/truc/myu.flags; // "muy" +/toto/gi.flags; // "gi" +/truc/muy.flags; // "muy" ``` ## Prothèse d'émulation (_polyfill_) ```js if (RegExp.prototype.flags === undefined) { - Object.defineProperty(RegExp.prototype, 'flags', { + Object.defineProperty(RegExp.prototype, "flags", { configurable: true, - get: function() { + get: function () { return this.toString().match(/[gimuy]*$/)[0]; - } + }, }); } ``` diff --git a/files/fr/web/javascript/reference/global_objects/regexp/global/index.md b/files/fr/web/javascript/reference/global_objects/regexp/global/index.md index bc73bed7fdedcd..ae3cd24c6b2f9c 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/global/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/global/index.md @@ -23,15 +23,15 @@ var regex = new RegExp("toto", "g"); console.log(regex.global); // true -var str = 'totoexempletoto'; -var str1 = str.replace(regex, ''); +var str = "totoexempletoto"; +var str1 = str.replace(regex, ""); -console.log(str1); // affichera "exemple" dans la console +console.log(str1); // affichera "exemple" dans la console -var regex1 = new RegExp('toto'); -var str2 = str.replace(regex1, ''); +var regex1 = new RegExp("toto"); +var str2 = str.replace(regex1, ""); -console.log(str2); // affichera "exempletoto" dans la console +console.log(str2); // affichera "exempletoto" dans la console ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/regexp/hasindices/index.md b/files/fr/web/javascript/reference/global_objects/regexp/hasindices/index.md index 0235f0ad76c61a..0fd4949b5b0bae 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/hasindices/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/hasindices/index.md @@ -23,18 +23,18 @@ Cette propriété ne peut être modifiée directement. ### Utiliser `hasIndices` ```js -const str1 = 'toto truc toto'; +const str1 = "toto truc toto"; -const regex1 = new RegExp('toto', 'gd'); +const regex1 = new RegExp("toto", "gd"); console.log(regex1.hasIndices); // Affiche : true console.log(regex1.exec(str1).indices[0]); // Affiche : Array [0, 3] console.log(regex1.exec(str1).indices[0]); // Affiche : Array [8, 11] -const str2 = 'toto truc toto'; +const str2 = "toto truc toto"; -const regex2 = new RegExp('toto'); +const regex2 = new RegExp("toto"); console.log(regex2.hasIndices); // Affiche : false diff --git a/files/fr/web/javascript/reference/global_objects/regexp/index.md b/files/fr/web/javascript/reference/global_objects/regexp/index.md index 9a80928dfc30cd..655c1115f40bda 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/index.md @@ -22,9 +22,9 @@ Il existe deux façons de créer un objet `RegExp` : une _notation littéra Ainsi, les expressions suivantes créent le même objet d'expression rationnelle : ```js -/ab+c/i; // notation littérale -new RegExp('ab+c', 'i'); // constructeur -new RegExp(/ab+c/, 'i'); // notation littérale dans un constructeur +/ab+c/i; // notation littérale +new RegExp("ab+c", "i"); // constructeur +new RegExp(/ab+c/, "i"); // notation littérale dans un constructeur ``` La notation littérale effectue la compilation de l'expression rationnelle lorsque l'expression est évaluée. Utilisez la notation littérale lorsque l'expression rationnelle reste constante. Par exemple, si vous utilisez la notation littérale pour construire une expression rationnelle utilisée dans une boucle, l'expression rationnelle ne sera pas recompilée à chaque itération. @@ -41,7 +41,7 @@ Par exemple, les définitions suivantes sont équivalentes : ```js var re = /\w+/; -var re = new RegExp('\\w+'); +var re = new RegExp("\\w+"); ``` ### Propriétés semblables à Perl @@ -112,8 +112,8 @@ On utilise des parenthèses capturantes pour pouvoir utiliser les correspondance ```js let re = /(\w+)\s(\w+)/; -let chaine = 'Alain Dupont'; -let nouvelleChaine = chaine.replace(re, '$2, $1'); +let chaine = "Alain Dupont"; +let nouvelleChaine = chaine.replace(re, "$2, $1"); console.log(nouvelleChaine); // Dupont, Alain ``` @@ -123,7 +123,7 @@ console.log(nouvelleChaine); La fin de ligne par défaut dépend de la plateforme (Unix, Windows, etc.). Cette méthode de découpage fournie permet de découper indépendamment de la plateforme utilisée. ```js -let texte = 'Un texte\net un autre\r\npuis ensuite\rla fin'; +let texte = "Un texte\net un autre\r\npuis ensuite\rla fin"; let lignes = texte.split(/\r\n|\r|\n/); console.log(lignes); // affiche [ 'Un texte', 'et un autre', 'puis ensuite', 'la fin' ] ``` @@ -133,7 +133,7 @@ On notera que l'ordre des modèles dans l'expression rationnelle est important. ### Utiliser une expression rationnelle sur plusieurs lignes ```js -let s = 'Et voici\nune autre ligne !'; +let s = "Et voici\nune autre ligne !"; s.match(/voici.*ligne/); // Renvoie null @@ -147,7 +147,7 @@ s.match(/voici[^]*ligne/); Cet exemple illustre comment on peut utiliser le marqueur [`sticky`](/fr/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) qui recherche une correspondance après [`RegExp.prototype.lastIndex`](/fr/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex). ```js -let str = '#toto#'; +let str = "#toto#"; let regex = /toto/y; regex.lastIndex = 1; @@ -163,7 +163,8 @@ Avec le marqueur d'adhérence `y`, la prochaine correspondance doit être placé ```js re = /\d/y; -while (r = re.exec("123 456")) console.log(r, "ET re.lastIndex", re.lastIndex); +while ((r = re.exec("123 456"))) + console.log(r, "ET re.lastIndex", re.lastIndex); // [ '1', index: 0, input: '123 456', groups: undefined ] ET re.lastIndex 1 // [ '2', index: 1, input: '123 456', groups: undefined ] ET re.lastIndex 2 @@ -182,15 +183,15 @@ Pour effectuer des correspondances sur d'autres caractères (par exemple les car Cet exemple illustre comment il est possible de séparer les caractères Unicode d'un mot. ```js -let texte = 'Образец text на русском языке'; +let texte = "Образец text на русском языке"; let regex = /[\u0400-\u04FF]+/g; let corresp = regex.exec(texte); -console.log(corresp[0]); // affiche 'Образец' +console.log(corresp[0]); // affiche 'Образец' console.log(regex.lastIndex); // affiche '7' let corresp2 = regex.exec(texte); -console.log(corresp2[0]); // affiche 'на' (n'affiche pas text +console.log(corresp2[0]); // affiche 'на' (n'affiche pas text console.log(regex.lastIndex); // affiche '15' // et ainsi de suite @@ -201,7 +202,7 @@ Les [échappements de propriété Unicode](/fr/docs/Web/JavaScript/Guide/Regular ### Extraire un sous-domaine d'une URL ```js -let url = 'http://xxx.domaine.com'; +let url = "http://xxx.domaine.com"; console.log(/[^.]+/.exec(url)[0].substr(7)); // affiche 'xxx' ``` @@ -221,12 +222,12 @@ console.log(/[^.]+/.exec(url)[0].substr(7)); // affiche 'xxx' ```js // Firefox 33 ou antérieur -'x'.replace(/x(.)?/g, function(m, group) { +"x".replace(/x(.)?/g, function (m, group) { console.log("'group:" + group + "'"); }); // 'group:' // Firefox 34 ou supérieur -'x'.replace(/x(.)?/g, function(m, group) { +"x".replace(/x(.)?/g, function (m, group) { console.log("'group:" + group + "'"); }); // 'group:undefined' ``` diff --git a/files/fr/web/javascript/reference/global_objects/regexp/input/index.md b/files/fr/web/javascript/reference/global_objects/regexp/input/index.md index d160e93c1f7eb7..148fc0dda853a2 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/input/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/input/index.md @@ -11,8 +11,8 @@ La propriété non-standard **`input`** est une propriété statique de l'expres ## Syntaxe ```js -RegExp.input -RegExp.$_ +RegExp.input; +RegExp.$_; ``` ## Description @@ -28,11 +28,11 @@ La valeur de la propriété **`input`** est modifiée à chaque fois que la cha ```js var re = /coucou/g; re.test("coucou toi !"); -RegExp.input; // "coucou toi !" -re.test("toto"); // nouveau test, pas de correspondance -RegExp.$_; // "coucou toi !" +RegExp.input; // "coucou toi !" +re.test("toto"); // nouveau test, pas de correspondance +RegExp.$_; // "coucou toi !" re.test("coucou monde !"); // nouveau test avec correspondance -RegExp.$_; // "coucou monde !" +RegExp.$_; // "coucou monde !" ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/regexp/lastindex/index.md b/files/fr/web/javascript/reference/global_objects/regexp/lastindex/index.md index 08010ed618baf4..3b6071ece2fc88 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/lastindex/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/lastindex/index.md @@ -13,7 +13,7 @@ La propriété **`lastIndex`** est un entier en lecture/écriture qui permet de ## Syntaxe ```js -regExpObj.lastIndex +regExpObj.lastIndex; ``` ## Description @@ -36,14 +36,14 @@ var re = /(hi)?/g; Correspond à la chaîne vide. ```js -console.log(re.exec('hi')); +console.log(re.exec("hi")); console.log(re.lastIndex); ``` Renvoie `["hi", "hi"]` avec `lastIndex` égal à 2. ```js -console.log(re.exec('hi')); +console.log(re.exec("hi")); console.log(re.lastIndex); ``` diff --git a/files/fr/web/javascript/reference/global_objects/regexp/lastmatch/index.md b/files/fr/web/javascript/reference/global_objects/regexp/lastmatch/index.md index cb9eb9cd93bae3..924d7afebad6b8 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/lastmatch/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/lastmatch/index.md @@ -11,8 +11,8 @@ La propriété non-standard **`lastMatch`** est une propriété statique en lect ## Syntaxe ```js -RegExp.lastMatch -RegExp['$&'] +RegExp.lastMatch; +RegExp["$&"]; ``` ## Description @@ -31,7 +31,7 @@ Il n'est pas possible d'utiliser l'alias avec la notation utilisant le point pou var re = /coucou/g; re.test("coucou toi!"); RegExp.lastMatch; // "coucou" -RegExp['$&']; // "coucou" +RegExp["$&"]; // "coucou" ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/regexp/lastparen/index.md b/files/fr/web/javascript/reference/global_objects/regexp/lastparen/index.md index ea89418fa711dc..60ee88f557f3cc 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/lastparen/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/lastparen/index.md @@ -11,8 +11,8 @@ La propriété **`lastParen`** est une propriété statique accessible en lectur ## Syntaxe ```js -RegExp.lastParen -RegExp['$+'] +RegExp.lastParen; +RegExp["$+"]; ``` ## Description @@ -31,7 +31,7 @@ Cet alias ne peut pas être utilisé avec la notation utilisant le point pour l' var re = /(coucou)/g; re.test("coucou toi !"); RegExp.lastParen; // "coucou" -RegExp['$+']; // "coucou" +RegExp["$+"]; // "coucou" ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/regexp/leftcontext/index.md b/files/fr/web/javascript/reference/global_objects/regexp/leftcontext/index.md index 32952cf3983d67..bd15aa0ec43cce 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/leftcontext/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/leftcontext/index.md @@ -11,13 +11,13 @@ La propriété non-standard **`leftContext`** est une propriété statique acces ## Syntaxe ```js -RegExp.leftContext -RegExp['$`'] +RegExp.leftContext; +RegExp["$`"]; ``` ## Description -La propriété `leftContext` est une propriété statique, elle n'est donc pas distincte entre les différents objets représentants les expressions rationnelles. Il faut donc toujours utiliser la syntaxe `RegExp.leftContext` ou `` RegExp['$`']. `` +La propriété `leftContext` est une propriété statique, elle n'est donc pas distincte entre les différents objets représentants les expressions rationnelles. Il faut donc toujours utiliser la syntaxe `RegExp.leftContext` ou ``RegExp['$`'].`` La valeur de la propriété `leftContext` n'est accessible uniquement qu'en lecture. Elle est modifiée par le moteur à chaque fois qu'une nouvelle correspondance est trouvée. @@ -29,7 +29,7 @@ L'alias ne peut pas être utilisé avec la notation utilisant le point (`` RegEx var re = /monde/g; re.test("coucou monde !"); RegExp.leftContext; // "coucou " -RegExp['$`']; // "coucou " +RegExp["$`"]; // "coucou " ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/regexp/n/index.md b/files/fr/web/javascript/reference/global_objects/regexp/n/index.md index 1dc5651d2bd88b..ebc619d6fab90c 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/n/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/n/index.md @@ -11,15 +11,15 @@ Les propriétés non-standard **$1, $2, $3, $4, $5, $6, $7, $8, $9** sont des pr ## Syntaxe ```js -RegExp.$1 -RegExp.$2 -RegExp.$3 -RegExp.$4 -RegExp.$5 -RegExp.$6 -RegExp.$7 -RegExp.$8 -RegExp.$9 +RegExp.$1; +RegExp.$2; +RegExp.$3; +RegExp.$4; +RegExp.$5; +RegExp.$6; +RegExp.$7; +RegExp.$8; +RegExp.$9; ``` ## Description @@ -38,8 +38,8 @@ Dans le script qui suit, on utilise {{jsxref("String.prototype.replace()", "repl ```js var re = /(\w+)\s(\w+)/; -var str = 'Jean Biche'; -str.replace(re, '$2, $1'); // "Biche, Jean" +var str = "Jean Biche"; +str.replace(re, "$2, $1"); // "Biche, Jean" RegExp.$1; // "Jean" RegExp.$2; // "Biche" ``` diff --git a/files/fr/web/javascript/reference/global_objects/regexp/regexp/index.md b/files/fr/web/javascript/reference/global_objects/regexp/regexp/index.md index 20d7e8599a1033..10fa30b8c2411a 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/regexp/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/regexp/index.md @@ -72,9 +72,9 @@ Il existe deux façons de créer un objet `RegExp` : en utilisant _une nota Les trois expressions suivantes permettent de créer la même expression rationnelle : ```js -/ab+c/i -new RegExp(/ab+c/, 'i') // Notation littérale -new RegExp('ab+c', 'i') // Constructeur +/ab+c/i; +new RegExp(/ab+c/, "i"); // Notation littérale +new RegExp("ab+c", "i"); // Constructeur ``` La notation littérale provoque la compilation de l'expression rationnelle lorsque l'expression est évaluée. On utilisera la notation littérale lorsque l'expression rationnelle demeure constante. Ainsi, si on utilise une notation littérale pour construire une expression rationnelle utilisée dans une boucle, l'expression rationnelle ne sera pas recompilée à chaque itération. diff --git a/files/fr/web/javascript/reference/global_objects/regexp/rightcontext/index.md b/files/fr/web/javascript/reference/global_objects/regexp/rightcontext/index.md index e4ea7eb8cc4f19..d3bc0d28104f5e 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/rightcontext/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/rightcontext/index.md @@ -11,8 +11,8 @@ La propriété non-standard **`rightContext`** est une propriété statique, acc ## Syntaxe ```js -RegExp.rightContext -RegExp["$'"] +RegExp.rightContext; +RegExp["$'"]; ``` ## Description @@ -29,7 +29,7 @@ L'alias ne peut pas être utilisé avec la syntaxe utilisant le point (`RegExp.$ var re = /coucou/g; re.test("coucou monde !"); RegExp.rightContext; // " monde !" -RegExp["$'"]; // " monde !" +RegExp["$'"]; // " monde !" ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/regexp/source/index.md b/files/fr/web/javascript/reference/global_objects/regexp/source/index.md index 225aafe7e6f8d7..0450f4eaa0b447 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/source/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/source/index.md @@ -15,7 +15,7 @@ La propriété **`source`** renvoie une chaîne de caractères qui contient le t ### Utiliser `source` ```js -var regex = /totoMachin/ig; +var regex = /totoMachin/gi; console.log(regex.source); // "totoMachin" ``` @@ -27,8 +27,8 @@ console.log(regex.source); // "totoMachin" ```js new RegExp().source; // "(?:)" -new RegExp('\n').source === "\n"; // true avant ES5 -new RegExp('\n').source === "\\n"; // true à partir d'ES5 +new RegExp("\n").source === "\n"; // true avant ES5 +new RegExp("\n").source === "\\n"; // true à partir d'ES5 ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/regexp/sticky/index.md b/files/fr/web/javascript/reference/global_objects/regexp/sticky/index.md index 891f80d6e9aee5..947a7e4a53cf4f 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/sticky/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/sticky/index.md @@ -21,7 +21,7 @@ La propriété `sticky` ne peut pas être modifiée directement. Elle est unique ### Utiliser une expression rationnelle avec le _flag_ _sticky_ ```js -var str = '#toto#'; +var str = "#toto#"; var regex = /toto/y; regex.lastIndex = 1; diff --git a/files/fr/web/javascript/reference/global_objects/regexp/test/index.md b/files/fr/web/javascript/reference/global_objects/regexp/test/index.md index 621b4de42db176..b7d9c5526aae60 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/test/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/test/index.md @@ -13,7 +13,7 @@ La méthode **`test()`** vérifie s'il y a une correspondance entre un texte et ## Syntaxe ```js -regexObj.test(chaîne) +regexObj.test(chaîne); ``` ### Paramètres @@ -44,18 +44,18 @@ console.log(resultat); // true L'exemple ci-dessous affiche un message qui dépend du succès du test : ```js -function testinput(regex, chaine){ - var midstring; - if (regex.test(chaine)) { - midstring = " contient "; - } else { - midstring = " ne contient pas "; - } - console.log(str + midstring + re.source); +function testinput(regex, chaine) { + var midstring; + if (regex.test(chaine)) { + midstring = " contient "; + } else { + midstring = " ne contient pas "; + } + console.log(str + midstring + re.source); } testinput(/^coucou/, "coucou le monde"); // coucou le monde contient coucou -testinput(/^coucou/, "salut le monde") // salut le monde ne contient pas coucou +testinput(/^coucou/, "salut le monde"); // salut le monde ne contient pas coucou ``` ### Utiliser `test()` avec le marqueur global (`/g`) diff --git a/files/fr/web/javascript/reference/global_objects/regexp/tostring/index.md b/files/fr/web/javascript/reference/global_objects/regexp/tostring/index.md index 75dc047a6ae476..aa2e8664750d04 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/tostring/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/tostring/index.md @@ -32,10 +32,10 @@ L'exemple qui suit affiche la chaîne correspondant à la valeur de l'objet {{js ```js var maRegExp = new RegExp("a+b+c"); -console.log(maRegExp.toString()); // affiche "/a+b+c/" +console.log(maRegExp.toString()); // affiche "/a+b+c/" var toto = new RegExp("truc", "g"); -console.log(toto.toString()); // affiche "/truc/g" +console.log(toto.toString()); // affiche "/truc/g" ``` ### Les expressions ratonnelles vides et l'échappement @@ -45,8 +45,8 @@ console.log(toto.toString()); // affiche "/truc/g" ```js new RegExp().toString(); // "(?:)" -new RegExp('\n').toString() === "/\n/"; // true avant ES5 -new RegExp('\n').toString() === "/\\n/"; // true à partir d'ES5 +new RegExp("\n").toString() === "/\n/"; // true avant ES5 +new RegExp("\n").toString() === "/\\n/"; // true à partir d'ES5 ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/regexp/unicode/index.md b/files/fr/web/javascript/reference/global_objects/regexp/unicode/index.md index a43fe41c9dbbeb..dce725d0279126 100644 --- a/files/fr/web/javascript/reference/global_objects/regexp/unicode/index.md +++ b/files/fr/web/javascript/reference/global_objects/regexp/unicode/index.md @@ -19,7 +19,7 @@ Cette propriété ne peut pas être modifiée directement. ## Exemples ```js -var regex = new RegExp('\u{61}', 'u'); +var regex = new RegExp("\u{61}", "u"); console.log(regex.unicode); // true ``` diff --git a/files/fr/web/javascript/reference/global_objects/set/@@iterator/index.md b/files/fr/web/javascript/reference/global_objects/set/@@iterator/index.md index 44f6a5d78e7f42..69e19ece30cbff 100644 --- a/files/fr/web/javascript/reference/global_objects/set/@@iterator/index.md +++ b/files/fr/web/javascript/reference/global_objects/set/@@iterator/index.md @@ -13,7 +13,7 @@ La valeur initiale de la propriété **`@@iterator`** est le même objet fonctio ## Syntaxe ```js -monSet[Symbol.iterator] +monSet[Symbol.iterator]; ``` ### Valeur de retour @@ -40,7 +40,7 @@ console.log(setIter.next().value); // {} ### Utiliser `[@@iterator]()` avec une boucle `for..of` ```js -const monSet= new Set(); +const monSet = new Set(); monSet.add("0"); monSet.add(1); monSet.add({}); diff --git a/files/fr/web/javascript/reference/global_objects/set/@@species/index.md b/files/fr/web/javascript/reference/global_objects/set/@@species/index.md index 08da15a15b9bb5..09a5f50814bcef 100644 --- a/files/fr/web/javascript/reference/global_objects/set/@@species/index.md +++ b/files/fr/web/javascript/reference/global_objects/set/@@species/index.md @@ -11,7 +11,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Set/@@species ## Syntaxe ```js -Set[Symbol.species] +Set[Symbol.species]; ``` ## Description diff --git a/files/fr/web/javascript/reference/global_objects/set/clear/index.md b/files/fr/web/javascript/reference/global_objects/set/clear/index.md index e5c4ce590e1627..11789a5dbe855f 100644 --- a/files/fr/web/javascript/reference/global_objects/set/clear/index.md +++ b/files/fr/web/javascript/reference/global_objects/set/clear/index.md @@ -27,13 +27,13 @@ var monSet = new Set(); monSet.add(1); monSet.add("toto"); -monSet.size; // 2 +monSet.size; // 2 monSet.has("toto"); // true monSet.clear(); -monSet.size; // 0 -monSet.has("truc") // false +monSet.size; // 0 +monSet.has("truc"); // false ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/set/delete/index.md b/files/fr/web/javascript/reference/global_objects/set/delete/index.md index e1088844a0f0fa..7028a9ab8d1762 100644 --- a/files/fr/web/javascript/reference/global_objects/set/delete/index.md +++ b/files/fr/web/javascript/reference/global_objects/set/delete/index.md @@ -36,20 +36,20 @@ monSet.add("toto"); monSet.delete("truc"); // Renvoie false. Aucun élément "truc" n'a pu être supprimé. monSet.delete("toto"); // Renvoie true. L'élément a pu être supprimé. -monSet.has("toto"); // Renvoie false. L'élément "toto" ne fait plus partie de l'ensemble. +monSet.has("toto"); // Renvoie false. L'élément "toto" ne fait plus partie de l'ensemble. ``` ### Utiliser `delete()` avec `forEach()` ```js var objetSet = new Set(); -objetSet.add({x: 10, y: 20}); // On ajoute un nouvel objet dans l'ensemble -objetSet.add({x: 20, y: 30}); // On ajoute un nouvel objet dans l'ensemble +objetSet.add({ x: 10, y: 20 }); // On ajoute un nouvel objet dans l'ensemble +objetSet.add({ x: 20, y: 30 }); // On ajoute un nouvel objet dans l'ensemble // On supprime les points de l'ensemble pour lesquels // x est supérieur à 10 -objetSet.forEach(function(point){ - if(point.x > 10){ +objetSet.forEach(function (point) { + if (point.x > 10) { objetSet.delete(point); } }); diff --git a/files/fr/web/javascript/reference/global_objects/set/entries/index.md b/files/fr/web/javascript/reference/global_objects/set/entries/index.md index 81d9fe9813aded..2b28b059099a31 100644 --- a/files/fr/web/javascript/reference/global_objects/set/entries/index.md +++ b/files/fr/web/javascript/reference/global_objects/set/entries/index.md @@ -13,7 +13,7 @@ La méthode **`entries()`** renvoie un nouvel objet [`Iterator`](/fr/docs/Web/Ja ## Syntaxe ```js -monSet.entries() +monSet.entries(); ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/set/foreach/index.md b/files/fr/web/javascript/reference/global_objects/set/foreach/index.md index 158be8a9367278..6ea7cd5c4b469e 100644 --- a/files/fr/web/javascript/reference/global_objects/set/foreach/index.md +++ b/files/fr/web/javascript/reference/global_objects/set/foreach/index.md @@ -58,7 +58,7 @@ Le code qui suit permet d'enregistrer une ligne pour chaque élément contenu da ```js function logSetElements(valeur1, valeur2, set) { - console.log("s[" + valeur1 + "] = " + valeur2); + console.log("s[" + valeur1 + "] = " + valeur2); } new Set(["toto", "truc", undefined]).forEach(logSetElements); diff --git a/files/fr/web/javascript/reference/global_objects/set/has/index.md b/files/fr/web/javascript/reference/global_objects/set/has/index.md index 2b8a0ccac847a5..7fff4bd113a3fc 100644 --- a/files/fr/web/javascript/reference/global_objects/set/has/index.md +++ b/files/fr/web/javascript/reference/global_objects/set/has/index.md @@ -33,16 +33,16 @@ Un booléen : `true` s'il existe un élément avec la valeur donnée au sein du var monSet = new Set(); monSet.add("toto"); -monSet.has("toto"); // renvoie true -monSet.has("truc"); // renvoie false +monSet.has("toto"); // renvoie true +monSet.has("truc"); // renvoie false var set1 = new Set(); -var obj1 = {'cle1': 1}; +var obj1 = { cle1: 1 }; set1.add(obj1); -set1.has(obj1); // renvoie true -set1.has({'cle1': 1}); // renvoie false car ce sont deux objets distincts -set1.add({'cle1': 1}); // set1 contient désormais 2 éléments +set1.has(obj1); // renvoie true +set1.has({ cle1: 1 }); // renvoie false car ce sont deux objets distincts +set1.add({ cle1: 1 }); // set1 contient désormais 2 éléments ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/set/index.md b/files/fr/web/javascript/reference/global_objects/set/index.md index 3886c06d586d17..7db4785c693810 100644 --- a/files/fr/web/javascript/reference/global_objects/set/index.md +++ b/files/fr/web/javascript/reference/global_objects/set/index.md @@ -57,6 +57,7 @@ Chaque valeur d'un `Set` doit être unique, il faut donc tester l'égalité des - [`Set.prototype.keys()`](/fr/docs/Web/JavaScript/Reference/Global_Objects/Set/values) - : Un alias pour [`Set.prototype.values()`](/fr/docs/Web/JavaScript/Reference/Global_Objects/Set/values). - [`Set.prototype.entries()`](/fr/docs/Web/JavaScript/Reference/Global_Objects/Set/entries) + - : Renvoie un nouvel objet itérateur qui contient **un tableau `[valeur, valeur]`** pour chaque élément de l'objet `Set`, selon leur ordre d'insertion. Il s'agit d'une méthode analogue à celle disponible pour [`Map`](/fr/docs/Web/JavaScript/Reference/Global_Objects/Map), c'est pour ça qu'on a le doublonnement de la valeur à la place de la clé. @@ -71,29 +72,29 @@ Chaque valeur d'un `Set` doit être unique, il faut donc tester l'égalité des ```js const monSet = new Set(); -monSet.add(1); // { 1 } -monSet.add(5); // { 1, 5 } -monSet.add(5); // { 1, 5 } -monSet.add('du texte'); // { 1, 5, 'du texte' } +monSet.add(1); // { 1 } +monSet.add(5); // { 1, 5 } +monSet.add(5); // { 1, 5 } +monSet.add("du texte"); // { 1, 5, 'du texte' } -const o = {a: 1, b: 2}; +const o = { a: 1, b: 2 }; monSet.add(o); -monSet.add({a: 1, b: 2}); +monSet.add({ a: 1, b: 2 }); // o fait référence à un objet différent // il n'y a pas de problème pour cet ajout monSet.has(1); // true monSet.has(3); // false, 3 n'a pas été ajouté à l'ensemble -monSet.has(5); // true -monSet.has(Math.sqrt(25)); // true -monSet.has('Du Texte'.toLowerCase()); // true +monSet.has(5); // true +monSet.has(Math.sqrt(25)); // true +monSet.has("Du Texte".toLowerCase()); // true monSet.has(o); // true monSet.size; // 5 monSet.delete(5); // retire 5 du set -monSet.has(5); // false, 5 a été retiré de l'ensemble +monSet.has(5); // false, 5 a été retiré de l'ensemble monSet.size; // 4, on a retiré une valeur de l'ensemble console.log(monSet); @@ -119,11 +120,11 @@ for (let item of monSet.values()) console.log(item); for (let [clé, valeur] of monSet.entries()) console.log(clé); // Une méthode de conversion avec Array.from -const monTableau = Array.from(monSet); // [1, "du texte", {"a": 1, "b": 2}, {"a": 1, "b": 2}] +const monTableau = Array.from(monSet); // [1, "du texte", {"a": 1, "b": 2}, {"a": 1, "b": 2}] // Cela fonctionnera également dans un document HTML monSet.add(document.body); -monSet.has(document.querySelector('body')); // true +monSet.has(document.querySelector("body")); // true // convertir un tableau (Array) en ensemble (Set) et vice versa const monSet2 = new Set([1, 2, 3, 4]); @@ -131,13 +132,13 @@ monSet2.size; // 4 [...monSet2]; // [1, 2, 3, 4] // L'intersection peut être calculée avec -const intersection = new Set([...set1].filter(x => set2.has(x))); +const intersection = new Set([...set1].filter((x) => set2.has(x))); // La différence pourra être simulée avec -const différence = new Set([...set1].filter(x => !set2.has(x))); +const différence = new Set([...set1].filter((x) => !set2.has(x))); // On peut itérer sur les entrées d'un ensemble avec forEach -mySet.forEach(function(value) { +mySet.forEach(function (value) { console.log(value); }); @@ -202,11 +203,11 @@ const setA = new Set([1, 2, 3, 4]); const setB = new Set([2, 3]); const setC = new Set([3, 4, 5, 6]); -isSuperset(setA, setB); // => true -union(setA, setC); // => Set [1, 2, 3, 4, 5, 6] -intersection(setA, setC); // => Set [3, 4] +isSuperset(setA, setB); // => true +union(setA, setC); // => Set [1, 2, 3, 4, 5, 6] +intersection(setA, setC); // => Set [3, 4] symmetricDifference(setA, setC); // => Set {1, 2, 5, 6} -difference(setA, setC); // => Set [1, 2] +difference(setA, setC); // => Set [1, 2] ``` ### Relations avec les objets `Array` @@ -218,9 +219,9 @@ let monTableau = ["valeur1", "valeur2", "valeur3"]; // un Array en Set let monSet = new Set(monTableau); -monSet.has('valeur1'); // renvoie true +monSet.has("valeur1"); // renvoie true -// Et utiliser l'opérateur de décomposition pour +// Et utiliser l'opérateur de décomposition pour // transformer un Set en Array. console.log([...monSet]); // affichera la même chose que monTableau ``` @@ -228,7 +229,7 @@ console.log([...monSet]); // affichera la même chose que monTableau ### Dédoublonner un tableau ```js -const nombres = [2,3,4,4,2,2,2,4,4,5,5,6,6,7,5,32,3,4,5]; +const nombres = [2, 3, 4, 4, 2, 2, 2, 4, 4, 5, 5, 6, 6, 7, 5, 32, 3, 4, 5]; console.log([...new Set(nombres)]); @@ -238,7 +239,7 @@ console.log([...new Set(nombres)]); ### Les relations avec les objets `String` ```js -let texte = 'India'; +let texte = "India"; const monSet = new Set(texte); // Set(5) {'I', 'n', 'd', 'i', 'a'} @@ -247,21 +248,19 @@ monSet.size; // 5 // Sensibilité à la casse -new Set('Firefox'); +new Set("Firefox"); // Set(7) { "F", "i", "r", "e", "f", "o", "x" } -new Set('firefox'); +new Set("firefox"); // Set(6) { "f", "i", "r", "e", "o", "x" } ``` ### Utilisation de `Set` pour vérifier l'unicité des valeurs d'une liste ```js -const tableau = Array - .from(document.querySelectorAll('[id]')) - .map(function(e) { - return e.id; - }); +const tableau = Array.from(document.querySelectorAll("[id]")).map(function (e) { + return e.id; +}); const set = new Set(tableau); console.assert(set.size == tableau.length); diff --git a/files/fr/web/javascript/reference/global_objects/set/set/index.md b/files/fr/web/javascript/reference/global_objects/set/set/index.md index a416d94265d8e3..7c723f345810fe 100644 --- a/files/fr/web/javascript/reference/global_objects/set/set/index.md +++ b/files/fr/web/javascript/reference/global_objects/set/set/index.md @@ -13,8 +13,8 @@ Le **constructeur `Set()`** permet de créer des objets `Set` qui sont des ensem ## Syntaxe ```js -new Set() -new Set(iterable) +new Set(); +new Set(iterable); ``` ### Paramètres @@ -34,13 +34,13 @@ Un nouvel objet `Set`. ### Utiliser `Set()` ```js -let monSet = new Set() +let monSet = new Set(); -monSet.add(1); // Set [ 1 ] -monSet.add(5); // Set [ 1, 5 ] -monSet.add(5); // Set [ 1, 5 ] -monSet.add('du texte'); // Set [ 1, 5, 'du texte' ] -let o = {a: 1, b: 2}; +monSet.add(1); // Set [ 1 ] +monSet.add(5); // Set [ 1, 5 ] +monSet.add(5); // Set [ 1, 5 ] +monSet.add("du texte"); // Set [ 1, 5, 'du texte' ] +let o = { a: 1, b: 2 }; monSet.add(o); ``` diff --git a/files/fr/web/javascript/reference/global_objects/set/size/index.md b/files/fr/web/javascript/reference/global_objects/set/size/index.md index 8e3fc6ab55363e..58bf23973bc430 100644 --- a/files/fr/web/javascript/reference/global_objects/set/size/index.md +++ b/files/fr/web/javascript/reference/global_objects/set/size/index.md @@ -20,7 +20,7 @@ La valeur de `size` est un entier représentant le nombre d'éléments contenus var monSet = new Set(); monSet.add(1); monSet.add(5); -monSet.add("du texte") +monSet.add("du texte"); monSet.size; // 3 ``` diff --git a/files/fr/web/javascript/reference/global_objects/sharedarraybuffer/bytelength/index.md b/files/fr/web/javascript/reference/global_objects/sharedarraybuffer/bytelength/index.md index d0ad50c5bd0701..8b9c1248df000f 100644 --- a/files/fr/web/javascript/reference/global_objects/sharedarraybuffer/bytelength/index.md +++ b/files/fr/web/javascript/reference/global_objects/sharedarraybuffer/bytelength/index.md @@ -13,7 +13,7 @@ La propriété d'accesseur **`byteLength`** représente la longueur d'un {{jsxre ## Syntaxe ```js -sab.byteLength +sab.byteLength; ``` ## Description diff --git a/files/fr/web/javascript/reference/global_objects/sharedarraybuffer/index.md b/files/fr/web/javascript/reference/global_objects/sharedarraybuffer/index.md index 5916cc69a60d8c..bef9a0b17beba1 100644 --- a/files/fr/web/javascript/reference/global_objects/sharedarraybuffer/index.md +++ b/files/fr/web/javascript/reference/global_objects/sharedarraybuffer/index.md @@ -34,7 +34,7 @@ La mémoire partagée peut être créée et mise à jour de façon simultanée e ### Contraintes de sécurité -La mémoire partagée et les chronomètres de haute précision ont été [désactivés début 2018](https://blog.mozilla.org/security/2018/01/03/mitigations-landing-new-class-timing-attack/) suite à la vulnérabilité [Spectre](https://fr.wikipedia.org/wiki/Spectre_(vulnérabilité)). En 2020, une nouvelle approche, sécurisée, a été mise en place afin de réactiver la mémoire partagée. En suivant quelques règles de sécurité, [`postMessage()`](/fr/docs/Web/API/Window/postMessage) ne lève plus d'exception pour les objets `SharedArrayBuffer` et une mémoire partagée entre les threads est disponible. +La mémoire partagée et les chronomètres de haute précision ont été [désactivés début 2018](https://blog.mozilla.org/security/2018/01/03/mitigations-landing-new-class-timing-attack/) suite à la vulnérabilité [Spectre](). En 2020, une nouvelle approche, sécurisée, a été mise en place afin de réactiver la mémoire partagée. En suivant quelques règles de sécurité, [`postMessage()`](/fr/docs/Web/API/Window/postMessage) ne lève plus d'exception pour les objets `SharedArrayBuffer` et une mémoire partagée entre les threads est disponible. Pour commencer, le document doit être mis à disposition dans [un contexte sécurisé](/fr/docs/Web/Security/Secure_Contexts). @@ -100,17 +100,17 @@ let sab = new SharedArrayBuffer(1024); ### Découper un objet `SharedArrayBuffer` ```js -sab.slice(); // SharedArrayBuffer { byteLength: 1024 } -sab.slice(2); // SharedArrayBuffer { byteLength: 1022 } -sab.slice(-2); // SharedArrayBuffer { byteLength: 2 } +sab.slice(); // SharedArrayBuffer { byteLength: 1024 } +sab.slice(2); // SharedArrayBuffer { byteLength: 1022 } +sab.slice(-2); // SharedArrayBuffer { byteLength: 2 } sab.slice(0, 1); // SharedArrayBuffer { byteLength: 1 } ``` ### Utiliser un tampon WebGL ```js -const canvas = document.querySelector('canvas'); -const gl = canvas.getContext('webgl'); +const canvas = document.querySelector("canvas"); +const gl = canvas.getContext("webgl"); const buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, sab, gl.STATIC_DRAW); diff --git a/files/fr/web/javascript/reference/global_objects/sharedarraybuffer/sharedarraybuffer/index.md b/files/fr/web/javascript/reference/global_objects/sharedarraybuffer/sharedarraybuffer/index.md index 191095eb3ad628..1e6adff935bab3 100644 --- a/files/fr/web/javascript/reference/global_objects/sharedarraybuffer/sharedarraybuffer/index.md +++ b/files/fr/web/javascript/reference/global_objects/sharedarraybuffer/sharedarraybuffer/index.md @@ -15,8 +15,8 @@ Le **constructeur `SharedArrayBuffer()`** permet de créer un objet [`SharedArra ## Syntaxe ```js -new SharedArrayBuffer() -new SharedArrayBuffer(longueur) +new SharedArrayBuffer(); +new SharedArrayBuffer(longueur); ``` ### Paramètres diff --git a/files/fr/web/javascript/reference/global_objects/sharedarraybuffer/slice/index.md b/files/fr/web/javascript/reference/global_objects/sharedarraybuffer/slice/index.md index 716f9f6560aa63..cd60e6cc102531 100644 --- a/files/fr/web/javascript/reference/global_objects/sharedarraybuffer/slice/index.md +++ b/files/fr/web/javascript/reference/global_objects/sharedarraybuffer/slice/index.md @@ -13,9 +13,9 @@ La méthode **`SharedArrayBuffer.prototype.slice()`** renvoie un nouvel objet {{ ## Syntaxe ```js -sab.slice() -sab.slice(début) -sab.slice(début, fin) +sab.slice(); +sab.slice(début); +sab.slice(début, fin); ``` ### Paramètres @@ -46,10 +46,10 @@ Un nouvel objet {{jsxref("SharedArrayBuffer")}} qui contient les éléments extr ```js var sab = new SharedArrayBuffer(1024); -sab.slice(); // SharedArrayBuffer { byteLength: 1024 } -sab.slice(2); // SharedArrayBuffer { byteLength: 1022 } -sab.slice(-2); // SharedArrayBuffer { byteLength: 2 } -sab.slice(0,1); // SharedArrayBuffer { byteLength: 1 } +sab.slice(); // SharedArrayBuffer { byteLength: 1024 } +sab.slice(2); // SharedArrayBuffer { byteLength: 1022 } +sab.slice(-2); // SharedArrayBuffer { byteLength: 2 } +sab.slice(0, 1); // SharedArrayBuffer { byteLength: 1 } ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/string/@@iterator/index.md b/files/fr/web/javascript/reference/global_objects/string/@@iterator/index.md index 452fe4b506a692..4c0fff69a0187a 100644 --- a/files/fr/web/javascript/reference/global_objects/string/@@iterator/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/@@iterator/index.md @@ -13,7 +13,7 @@ La méthode **`[@@iterator]()`** renvoie un nouvel objet [`Iterator`](/fr/docs/W ## Syntaxe ```js -chaîneDeCaractères[Symbol.iterator] +chaîneDeCaractères[Symbol.iterator]; ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/string/anchor/index.md b/files/fr/web/javascript/reference/global_objects/string/anchor/index.md index 47de9953e0f17a..1adc51ff722e27 100644 --- a/files/fr/web/javascript/reference/global_objects/string/anchor/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/anchor/index.md @@ -11,7 +11,7 @@ La méthode **`anchor()`** permet de créer une ancre HTML {{HTMLElement("a")}} ## Syntaxe ```js -str.anchor(name) +str.anchor(name); ``` ### Paramètres @@ -48,9 +48,9 @@ produira le code HTML suivant : ## Prothèse d'émulation (_polyfill_) ```js -if (!String.prototype.anchor){ - String.prototype.anchor = function(x){ - return '' + this + '' +if (!String.prototype.anchor) { + String.prototype.anchor = function (x) { + return '' + this + ""; }; } ``` diff --git a/files/fr/web/javascript/reference/global_objects/string/at/index.md b/files/fr/web/javascript/reference/global_objects/string/at/index.md index f4e2885f15b733..ac55266034cb58 100644 --- a/files/fr/web/javascript/reference/global_objects/string/at/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/at/index.md @@ -13,7 +13,7 @@ La méthode **`at()`** prend un entier en argument et renvoie une nouvelle chaî ## Syntaxe ```js -at(indice) +at(indice); ``` ### Paramètres @@ -37,12 +37,12 @@ function dernierCar(str) { return str.at(-1); } -let refFacture = 'maFacture01'; +let refFacture = "maFacture01"; console.log(dernierCar(refFacture)); // Affiche '1' dans la console -refFacture = 'maFacture02'; +refFacture = "maFacture02"; console.log(dernierCar(refFacture)); // Affiche '2' dans la console @@ -56,7 +56,7 @@ On compare ici différentes méthodes pour sélectionner l'avant-dernier caract const maChaine = "Vers l'infini et au-delà !"; // En utilisant la propriété length et la méthode charAt() -const avecLength = maChaine.charAt(maChaine.length-2); +const avecLength = maChaine.charAt(maChaine.length - 2); console.log(avecLength); // Affiche 'à' dans la console // En utilisant la méthode slice() diff --git a/files/fr/web/javascript/reference/global_objects/string/big/index.md b/files/fr/web/javascript/reference/global_objects/string/big/index.md index 4c0a63bac65167..9fc48c3d731a3c 100644 --- a/files/fr/web/javascript/reference/global_objects/string/big/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/big/index.md @@ -13,7 +13,7 @@ La méthode **`big()`** crée un élément HTML {{HTMLElement("big")}} qui affic ## Syntaxe ```js -str.big() +str.big(); ``` ### Valeur de retour @@ -32,15 +32,15 @@ L'exemple suivant montre les méthodes de `String` pour changer la taille d'une ```js var chaîneMonde = "Coucou monde"; -console.log( chaîneMonde.small() ); // Coucou monde -console.log( chaîneMonde.big() ); // Coucou monde -console.log( chaîneMonde.fontsize(7) ); // Coucou monde +console.log(chaîneMonde.small()); // Coucou monde +console.log(chaîneMonde.big()); // Coucou monde +console.log(chaîneMonde.fontsize(7)); // Coucou monde ``` Avec l'objet {{domxref("HTMLElement.style", "element.style")}}, il est possible d'accéder à l'attribut `style` de l'élément et de le manipuler. Par exemple : ```js -document.getElementById('idÉlément').style.fontSize = '2em' +document.getElementById("idÉlément").style.fontSize = "2em"; ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/string/blink/index.md b/files/fr/web/javascript/reference/global_objects/string/blink/index.md index 2aa641bea14950..938538f45bf107 100644 --- a/files/fr/web/javascript/reference/global_objects/string/blink/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/blink/index.md @@ -13,7 +13,7 @@ La méthode **`blink()`** crée un élément HTML {{HTMLElement("blink")}} qui a ## Syntaxe ```js -str.blink() +str.blink(); ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/string/bold/index.md b/files/fr/web/javascript/reference/global_objects/string/bold/index.md index a43dcc2ebe1edf..1e5e385e971e0a 100644 --- a/files/fr/web/javascript/reference/global_objects/string/bold/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/bold/index.md @@ -11,7 +11,7 @@ La méthode **`bold()`** crée un élément HTML {{HTMLElement("b")}} qui affich ## Syntaxe ```js -str.bold() +str.bold(); ``` ### Valeur de retour @@ -30,10 +30,10 @@ L'exemple suivant utilise des méthodes de `String` pour changer l'affichage de ```js var chaîneMonde = "Coucou monde"; -console.log( chaîneMonde.blink() ); -console.log( chaîneMonde.bold() ); -console.log( chaîneMonde.italics() ); -console.log( chaîneMonde.strike() ); +console.log(chaîneMonde.blink()); +console.log(chaîneMonde.bold()); +console.log(chaîneMonde.italics()); +console.log(chaîneMonde.strike()); ``` Cet exemple produit le même HTML que le code suivant : diff --git a/files/fr/web/javascript/reference/global_objects/string/charat/index.md b/files/fr/web/javascript/reference/global_objects/string/charat/index.md index e39e34a9c5803a..564aa1da272958 100644 --- a/files/fr/web/javascript/reference/global_objects/string/charat/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/charat/index.md @@ -13,7 +13,7 @@ La méthode **`charAt()`** renvoie une nouvelle chaîne contenant le caractère ## Syntaxe ```js -str.charAt(index) +str.charAt(index); ``` ### Paramètres @@ -38,11 +38,11 @@ L'exemple suivant affiche les caractères à différentes positions de la chaîn ```js var uneChaîne = "Coucou tout le monde"; -console.log("La caractère d'indice 0 est '" + uneChaîne.charAt(0) + "'"); -console.log("La caractère d'indice 1 est '" + uneChaîne.charAt(1) + "'"); -console.log("La caractère d'indice 2 est '" + uneChaîne.charAt(2) + "'"); -console.log("La caractère d'indice 3 est '" + uneChaîne.charAt(3) + "'"); -console.log("La caractère d'indice 4 est '" + uneChaîne.charAt(4) + "'"); +console.log("La caractère d'indice 0 est '" + uneChaîne.charAt(0) + "'"); +console.log("La caractère d'indice 1 est '" + uneChaîne.charAt(1) + "'"); +console.log("La caractère d'indice 2 est '" + uneChaîne.charAt(2) + "'"); +console.log("La caractère d'indice 3 est '" + uneChaîne.charAt(3) + "'"); +console.log("La caractère d'indice 4 est '" + uneChaîne.charAt(4) + "'"); console.log("La caractère d'indice 999 est '" + uneChaîne.charAt(999) + "'"); ``` @@ -115,8 +115,8 @@ function getWholeChar(str, i) { Dans un environnement ECMAScript 2016 qui permet d'utiliser l'affectation par décomposition, on peut obtenir une version plus succincte et flexible : ```js -var str = 'A\uD87E\uDC04Z'; // We could also use a non-BMP character directly -for (var i=0, chr; i < str.length; i++) { +var str = "A\uD87E\uDC04Z"; // We could also use a non-BMP character directly +for (var i = 0, chr; i < str.length; i++) { [chr, i] = getWholeCharAndI(str, i); // Adapt this line at the top of each loop, passing in the whole string and // the current iteration and returning an array with the individual character @@ -129,37 +129,37 @@ function getWholeCharAndI(str, i) { var code = str.charCodeAt(i); if (Number.isNaN(code)) { - return ''; // Position not found + return ""; // Position not found } - if (code < 0xD800 || code > 0xDFFF) { + if (code < 0xd800 || code > 0xdfff) { return [str.charAt(i), i]; // Normal character, keeping 'i' the same } // High surrogate (could change last hex to 0xDB7F to treat high private // surrogates as single characters) - if (0xD800 <= code && code <= 0xDBFF) { - if (str.length <= (i+1)) { - throw 'High surrogate without following low surrogate'; + if (0xd800 <= code && code <= 0xdbff) { + if (str.length <= i + 1) { + throw "High surrogate without following low surrogate"; } - var next = str.charCodeAt(i+1); - if (0xDC00 > next || next > 0xDFFF) { - throw 'High surrogate without following low surrogate'; - } - return [str.charAt(i)+str.charAt(i+1), i+1]; + var next = str.charCodeAt(i + 1); + if (0xdc00 > next || next > 0xdfff) { + throw "High surrogate without following low surrogate"; + } + return [str.charAt(i) + str.charAt(i + 1), i + 1]; } // Low surrogate (0xDC00 <= code && code <= 0xDFFF) if (i === 0) { - throw 'Low surrogate without preceding high surrogate'; + throw "Low surrogate without preceding high surrogate"; } - var prev = str.charCodeAt(i-1); + var prev = str.charCodeAt(i - 1); // (could change last hex to 0xDB7F to treat high private surrogates // as single characters) - if (0xD800 > prev || prev > 0xDBFF) { - throw 'Low surrogate without preceding high surrogate'; + if (0xd800 > prev || prev > 0xdbff) { + throw "Low surrogate without preceding high surrogate"; } // Return the next character instead (and increment) - return [str.charAt(i+1), i+1]; + return [str.charAt(i + 1), i + 1]; } ``` @@ -168,13 +168,13 @@ function getWholeCharAndI(str, i) { Si on souhaite récupérer les paires de codets des caractères hors du plan classique, on peut utiliser le code suivant : ```js -function fixedCharAt (str, idx) { - var ret = ''; - str += ''; +function fixedCharAt(str, idx) { + var ret = ""; + str += ""; var end = str.length; var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; - while ((surrogatePairs.exec(str)) != null) { + while (surrogatePairs.exec(str) != null) { var li = surrogatePairs.lastIndex; if (li - 2 < idx) { idx++; @@ -184,14 +184,17 @@ function fixedCharAt (str, idx) { } if (idx >= end || idx < 0) { - return ''; + return ""; } ret += str.charAt(idx); - if (/[\uD800-\uDBFF]/.test(ret) && /[\uDC00-\uDFFF]/.test(str.charAt(idx+1))) { + if ( + /[\uD800-\uDBFF]/.test(ret) && + /[\uDC00-\uDFFF]/.test(str.charAt(idx + 1)) + ) { // On avance d'un puisque l'un des caractères fait partie de la paire - ret += str.charAt(idx+1); + ret += str.charAt(idx + 1); } return ret; } diff --git a/files/fr/web/javascript/reference/global_objects/string/charcodeat/index.md b/files/fr/web/javascript/reference/global_objects/string/charcodeat/index.md index 1a7581b48137ba..f54d43c3bcdab8 100644 --- a/files/fr/web/javascript/reference/global_objects/string/charcodeat/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/charcodeat/index.md @@ -15,7 +15,7 @@ Le codet UTF-16 renvoyé correspond au codet Unicode si le caractère peut être ## Syntaxe ```js -str.charCodeAt(indice) +str.charCodeAt(indice); ``` ### Paramètres @@ -44,7 +44,7 @@ Dans les anciennes versions (JavaScript 1.2 par exemple) la méthode `charCodeAt L'exemple suivant retourne 65, la valeur Unicode de A. ```js -"ABC".charCodeAt(0) // returns 65 +"ABC".charCodeAt(0); // returns 65 ``` ### Utiliser charCodeAt pour gérer les caractères hors du plan multilingue de base sans hypothèse sur leur présence @@ -52,71 +52,72 @@ L'exemple suivant retourne 65, la valeur Unicode de A. Cette fonction peut être utilisée dans des boucles ou autres dans les cas où on ne sait pas si des caractères représentés sur deux demi-codets (hors du plan BMP) existent avant la position indiquée. ```js -function fixedCharCodeAt (str, idx) { - // ex. fixedCharCodeAt ('\uD800\uDC00', 0); // 65536 - // ex. fixedCharCodeAt ('\uD800\uDC00', 1); // false - idx = idx || 0; - var code = str.charCodeAt(idx); - var hi, low; - - // On gère le demi-codet supérieur (la borne supérieure - // utilisée pourrait être 0xDB7F afin de traiter les - // paires surrogates privées comme des caractères uniques) - if (0xD800 <= code && code <= 0xDBFF) { - hi = code; - low = str.charCodeAt(idx+1); - if (isNaN(low)) { - throw "Le demi-codet supérieur n'est pas suivi "+ - "par un demi-codet inférieur dans fixedCharCodeAt()"; - } - return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000; +function fixedCharCodeAt(str, idx) { + // ex. fixedCharCodeAt ('\uD800\uDC00', 0); // 65536 + // ex. fixedCharCodeAt ('\uD800\uDC00', 1); // false + idx = idx || 0; + var code = str.charCodeAt(idx); + var hi, low; + + // On gère le demi-codet supérieur (la borne supérieure + // utilisée pourrait être 0xDB7F afin de traiter les + // paires surrogates privées comme des caractères uniques) + if (0xd800 <= code && code <= 0xdbff) { + hi = code; + low = str.charCodeAt(idx + 1); + if (isNaN(low)) { + throw ( + "Le demi-codet supérieur n'est pas suivi " + + "par un demi-codet inférieur dans fixedCharCodeAt()" + ); } - if (0xDC00 <= code && code <= 0xDFFF) { + return (hi - 0xd800) * 0x400 + (low - 0xdc00) + 0x10000; + } + if (0xdc00 <= code && code <= 0xdfff) { // Demi-codet inférieur - // On renvoie false pour permettre aux boucles - // car le cas a normalement déjà été géré avec - // l'étape précédente - return false; - } - return code; + // On renvoie false pour permettre aux boucles + // car le cas a normalement déjà été géré avec + // l'étape précédente + return false; + } + return code; } ``` ### Utiliser `charCodeAt()` pour gérer les caractères du plan multilingue de base (en sachant qu'ils sont présents) ```js -function knownCharCodeAt (str, idx) { - str += ''; - var code, - end = str.length; - - var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; - while ((surrogatePairs.exec(str)) != null) { - var li = surrogatePairs.lastIndex; - if (li - 2 < idx) { - idx++; - } - else { - break; - } - } - - if (idx >= end || idx < 0) { - return NaN; - } - - code = str.charCodeAt(idx); - - var hi, low; - if (0xD800 <= code && code <= 0xDBFF) { - hi = code; - low = str.charCodeAt(idx+1); - // On prend un caractère de plus - // car on a deux demi-codets à récupérer - return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000; +function knownCharCodeAt(str, idx) { + str += ""; + var code, + end = str.length; + + var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + while (surrogatePairs.exec(str) != null) { + var li = surrogatePairs.lastIndex; + if (li - 2 < idx) { + idx++; + } else { + break; } - return code; + } + + if (idx >= end || idx < 0) { + return NaN; + } + + code = str.charCodeAt(idx); + + var hi, low; + if (0xd800 <= code && code <= 0xdbff) { + hi = code; + low = str.charCodeAt(idx + 1); + // On prend un caractère de plus + // car on a deux demi-codets à récupérer + return (hi - 0xd800) * 0x400 + (low - 0xdc00) + 0x10000; + } + return code; } ``` diff --git a/files/fr/web/javascript/reference/global_objects/string/codepointat/index.md b/files/fr/web/javascript/reference/global_objects/string/codepointat/index.md index 6c46f15ba3d2c2..e5ca6cccf6414c 100644 --- a/files/fr/web/javascript/reference/global_objects/string/codepointat/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/codepointat/index.md @@ -13,7 +13,7 @@ La méthode **`codePointAt()`** renvoie un entier positif qui correspond au code ## Syntaxe ```js -str.codePointAt(pos) +str.codePointAt(pos); ``` ### Paramètres @@ -32,10 +32,10 @@ S'il n'y a pas d'élément à la position donnée, la valeur renvoyée sera {{js ## Exemples ```js -'ABC'.codePointAt(1); // 66 -'\uD800\uDC00'.codePointAt(0); // 65536 +"ABC".codePointAt(1); // 66 +"\uD800\uDC00".codePointAt(0); // 65536 -'XYZ'.codePointAt(42); // undefined +"XYZ".codePointAt(42); // undefined ``` ## Prothèse d'émulation (_polyfill_) @@ -45,18 +45,18 @@ Le fragment de code suivant permet d'ajouter la méthode `codePointAt()` pour le ```js /*! https://mths.be/codepointat v0.2.0 by @mathias */ if (!String.prototype.codePointAt) { - (function() { - 'use strict'; // needed to support `apply`/`call` with `undefined`/`null` - var defineProperty = (function() { + (function () { + "use strict"; // needed to support `apply`/`call` with `undefined`/`null` + var defineProperty = (function () { // IE 8 only supports `Object.defineProperty` on DOM elements try { var object = {}; var $defineProperty = Object.defineProperty; var result = $defineProperty(object, object, object) && $defineProperty; - } catch(error) {} + } catch (error) {} return result; - }()); - var codePointAt = function(position) { + })(); + var codePointAt = function (position) { if (this == null) { throw TypeError(); } @@ -64,7 +64,8 @@ if (!String.prototype.codePointAt) { var size = string.length; // `ToInteger` var index = position ? Number(position) : 0; - if (index != index) { // better `isNaN` + if (index != index) { + // better `isNaN` index = 0; } // Account for out-of-bounds indices: @@ -74,28 +75,31 @@ if (!String.prototype.codePointAt) { // Get the first code unit var first = string.charCodeAt(index); var second; - if ( // check if it’s the start of a surrogate pair - first >= 0xD800 && first <= 0xDBFF && // high surrogate + if ( + // check if it’s the start of a surrogate pair + first >= 0xd800 && + first <= 0xdbff && // high surrogate size > index + 1 // there is a next code unit ) { second = string.charCodeAt(index + 1); - if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate + if (second >= 0xdc00 && second <= 0xdfff) { + // low surrogate // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae - return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + return (first - 0xd800) * 0x400 + second - 0xdc00 + 0x10000; } } return first; }; if (defineProperty) { - defineProperty(String.prototype, 'codePointAt', { - 'value': codePointAt, - 'configurable': true, - 'writable': true + defineProperty(String.prototype, "codePointAt", { + value: codePointAt, + configurable: true, + writable: true, }); } else { String.prototype.codePointAt = codePointAt; } - }()); + })(); } ``` diff --git a/files/fr/web/javascript/reference/global_objects/string/concat/index.md b/files/fr/web/javascript/reference/global_objects/string/concat/index.md index f271e7aeaccb2d..e8aca628a4948b 100644 --- a/files/fr/web/javascript/reference/global_objects/string/concat/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/concat/index.md @@ -39,11 +39,11 @@ console.log(coucou.concat("Tristan,", " bonne journée.")); /* Bonjour Tristan, bonne journée. */ -var salutation = ['Bonjour', ' ', 'Alfred', ' ', '!']; +var salutation = ["Bonjour", " ", "Alfred", " ", "!"]; "".concat(...salutation); // "Bonjour Alfred !" -"".concat({}); // [object Object] -"".concat([]); // "" +"".concat({}); // [object Object] +"".concat([]); // "" "".concat(null); // "null" "".concat(true); // "true" "".concat(4, 5); // "45" diff --git a/files/fr/web/javascript/reference/global_objects/string/endswith/index.md b/files/fr/web/javascript/reference/global_objects/string/endswith/index.md index ea5e9e67d53223..6e3e466bb325e4 100644 --- a/files/fr/web/javascript/reference/global_objects/string/endswith/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/endswith/index.md @@ -36,9 +36,9 @@ Cette méthode permet de savoir si une chaine de caractères se termine avec une ```js var str = "Être, ou ne pas être : telle est la question."; -console.log(str.endsWith("question.")); // true -console.log(str.endsWith("pas être")); // false -console.log(str.endsWith("pas être", 20)); // true +console.log(str.endsWith("question.")); // true +console.log(str.endsWith("pas être")); // false +console.log(str.endsWith("pas être", 20)); // true ``` ## Prothèse d'émulation (_polyfill_) @@ -47,9 +47,14 @@ Cette méthode a été ajoutée dans la spécification ECMAScript 6 et peut ne p ```js if (!String.prototype.endsWith) { - String.prototype.endsWith = function(searchString, position) { + String.prototype.endsWith = function (searchString, position) { var subjectString = this.toString(); - if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) { + if ( + typeof position !== "number" || + !isFinite(position) || + Math.floor(position) !== position || + position > subjectString.length + ) { position = subjectString.length; } position -= searchString.length; diff --git a/files/fr/web/javascript/reference/global_objects/string/fixed/index.md b/files/fr/web/javascript/reference/global_objects/string/fixed/index.md index 73c2d126862aed..90654d4c373bf1 100644 --- a/files/fr/web/javascript/reference/global_objects/string/fixed/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/fixed/index.md @@ -11,7 +11,7 @@ La méthode **`fixed()`** permet de créer un élément HTML {{HTMLElement("tt") ## Syntaxe ```js -str.fixed() +str.fixed(); ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/string/fontcolor/index.md b/files/fr/web/javascript/reference/global_objects/string/fontcolor/index.md index f869318b6c0799..5d1ad4d8919049 100644 --- a/files/fr/web/javascript/reference/global_objects/string/fontcolor/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/fontcolor/index.md @@ -13,7 +13,7 @@ La méthode **`fontcolor()`** permet de créer un élément {{HTMLElement("font" ## Syntaxe ```js -str.fontcolor(couleur) +str.fontcolor(couleur); ``` ### Paramètres @@ -36,17 +36,22 @@ L'exemple qui suit illustre comment utiliser la méthode `fontcolor()` pour modi ```js var worldString = "Coucou monde"; -console.log(worldString.fontcolor("red") + " avec le littéral red sur cette ligne"); +console.log( + worldString.fontcolor("red") + " avec le littéral red sur cette ligne", +); // 'Coucou monde avec le littéral red sur cette ligne' -console.log(worldString.fontcolor("FF00") + " avec la valeur hexadécimale sur cette ligne"); +console.log( + worldString.fontcolor("FF00") + + " avec la valeur hexadécimale sur cette ligne", +); // 'Coucou monde avec la valeur hexadécimale sur cette ligne' ``` L'objet {{domxref("HTMLElement.style", "element.style")}} permet d'utiliser l'attribut `style` de l'élément et de le manipuler de façon générique. Par exemple : ```js -document.getElementById('IDdeVotreElement').style.color = 'red' +document.getElementById("IDdeVotreElement").style.color = "red"; ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/string/fontsize/index.md b/files/fr/web/javascript/reference/global_objects/string/fontsize/index.md index de1f0e51ee3af3..6950ae973f7511 100644 --- a/files/fr/web/javascript/reference/global_objects/string/fontsize/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/fontsize/index.md @@ -13,7 +13,7 @@ La propriété **`fontsize()`** permet de créer un élément HTML {{HTMLElement ## Syntaxe ```js -str.fontsize(taille) +str.fontsize(taille); ``` ### Paramètres @@ -44,7 +44,7 @@ console.log(worldString.fontsize(7)); // Coucou monde L'objet {{domxref("HTMLElement.style", "element.style")}} permet d'utiliser l'attribut `style` de l'élément et de le manipuler de façon générique. Par exemple : ```js -document.getElementById('IdElement').style.fontSize = '0.7em' +document.getElementById("IdElement").style.fontSize = "0.7em"; ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/string/fromcharcode/index.md b/files/fr/web/javascript/reference/global_objects/string/fromcharcode/index.md index ff171a3c8d139d..16e87fa0683d42 100644 --- a/files/fr/web/javascript/reference/global_objects/string/fromcharcode/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/fromcharcode/index.md @@ -36,22 +36,22 @@ La méthode `fromCharCode()` étant une méthode statique de l'objet `String`, e Pour les caractères du plan multilingue de base, UTF-16 utilise une seule unité de code : ```js -String.fromCharCode(65,66,67); // ABC -String.fromCharCode(0x2014); // "—" -String.fromCharCode(0x12014); // "—" également, le 1 a été tronqué -String.fromCharCode(8212); // renvoie également "—" car 8212 - // est la forme décimale +String.fromCharCode(65, 66, 67); // ABC +String.fromCharCode(0x2014); // "—" +String.fromCharCode(0x12014); // "—" également, le 1 a été tronqué +String.fromCharCode(8212); // renvoie également "—" car 8212 +// est la forme décimale ``` Les caractères hors de ce plan utilisent deux unités de code (on parle de _surrogate pair_) : ```js -String.fromCharCode(0xD83C, 0xDF03); // Point de code U+1F303 pour l'émoji nuit étoilée +String.fromCharCode(0xd83c, 0xdf03); // Point de code U+1F303 pour l'émoji nuit étoilée // Forme décimale équivalente : String.fromCharCode(55356, 57091); -String.fromCharCode(0xD834, 0xDF06, 0x61, 0xD834, 0xDF07); +String.fromCharCode(0xd834, 0xdf06, 0x61, 0xd834, 0xdf07); // "\uD834\uDF06a\uD834\uDF07" ``` diff --git a/files/fr/web/javascript/reference/global_objects/string/fromcodepoint/index.md b/files/fr/web/javascript/reference/global_objects/string/fromcodepoint/index.md index dacac72917ce59..99b8bd614ac022 100644 --- a/files/fr/web/javascript/reference/global_objects/string/fromcodepoint/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/fromcodepoint/index.md @@ -38,19 +38,19 @@ Une chaîne de caractères créée à partir de la séquence de codets indiquée ### Utiliser `fromCodePoint()` ```js -String.fromCodePoint(42); // "*" -String.fromCodePoint(65, 90); // "AZ" -String.fromCodePoint(0x404); // "\u0404" -String.fromCodePoint(0x2F804); // "\uD87E\uDC04" -String.fromCodePoint(194564); // "\uD87E\uDC04" -String.fromCodePoint(0x1D306, 0x61, 0x1D307) // "\uD834\uDF06a\uD834\uDF07" - -String.fromCodePoint('_'); // RangeError +String.fromCodePoint(42); // "*" +String.fromCodePoint(65, 90); // "AZ" +String.fromCodePoint(0x404); // "\u0404" +String.fromCodePoint(0x2f804); // "\uD87E\uDC04" +String.fromCodePoint(194564); // "\uD87E\uDC04" +String.fromCodePoint(0x1d306, 0x61, 0x1d307); // "\uD834\uDF06a\uD834\uDF07" + +String.fromCodePoint("_"); // RangeError String.fromCodePoint(Infinity); // RangeError -String.fromCodePoint(-1); // RangeError -String.fromCodePoint(3.14); // RangeError -String.fromCodePoint(3e-2); // RangeError -String.fromCodePoint(NaN); // RangeError +String.fromCodePoint(-1); // RangeError +String.fromCodePoint(3.14); // RangeError +String.fromCodePoint(3e-2); // RangeError +String.fromCodePoint(NaN); // RangeError ``` ### Comparaison avec `fromCharCode()` @@ -58,14 +58,14 @@ String.fromCodePoint(NaN); // RangeError La méthode {{jsxref("String.fromCharCode()")}} ne peut pas renvoyer les caractères de l'intervalle 0x010000 à 0X10FFFF avec un seul codet, il est nécessaire de lui fournir la paire décomposée (_surrogate pair_) pour obtenr un tel caractère : ```js -String.fromCharCode(0xD83C, 0xDF03); // émoji « nuit étoilée » -String.fromCharCode(55356, 57091); // équivalent en notation décimale +String.fromCharCode(0xd83c, 0xdf03); // émoji « nuit étoilée » +String.fromCharCode(55356, 57091); // équivalent en notation décimale ``` `String.fromCodePoint()`, en revanche, peut renvoyer les caractères qui s'expriment sur plus d'un codet de 16 bits grâce à leur codet « simple » : ```js -String.fromCodePoint(0x1F303); // ou 127747 en notation décimale +String.fromCodePoint(0x1f303); // ou 127747 en notation décimale ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/string/includes/index.md b/files/fr/web/javascript/reference/global_objects/string/includes/index.md index 975d0e5ffb6c51..c78f19502166ec 100644 --- a/files/fr/web/javascript/reference/global_objects/string/includes/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/includes/index.md @@ -37,7 +37,7 @@ Cette méthode détermine si une chaîne de caractères est contenue dans une au `includes()` est sensible à la casse. Par exemple, l'expression suivante nous retournera `false` : ```js -'Baleine bleue'.includes('baleine'); // false +"Baleine bleue".includes("baleine"); // false ``` ## Exemples @@ -47,12 +47,12 @@ Cette méthode détermine si une chaîne de caractères est contenue dans une au ```js const str = "Être ou ne pas être, telle est la question."; -console.log(str.includes("Être")); // true -console.log(str.includes("question")); // true -console.log(str.includes("pléonasme")); // false -console.log(str.includes("Être", 1)); // false -console.log(str.includes("ÊTRE")); // false -console.log(str.includes("")); // true +console.log(str.includes("Être")); // true +console.log(str.includes("question")); // true +console.log(str.includes("pléonasme")); // false +console.log(str.includes("Être", 1)); // false +console.log(str.includes("ÊTRE")); // false +console.log(str.includes("")); // true ``` ## Prothèse d'émulation (_polyfill_) @@ -63,13 +63,15 @@ Cependant, vous pouvez facilement {{Glossary('polyfill')}} cette méthode pour d ```js if (!String.prototype.includes) { - String.prototype.includes = function(search, start) { - 'use strict'; + String.prototype.includes = function (search, start) { + "use strict"; if (search instanceof RegExp) { - throw TypeError('first argument must not be a RegExp'); + throw TypeError("first argument must not be a RegExp"); + } + if (start === undefined) { + start = 0; } - if (start === undefined) { start = 0; } return this.indexOf(search, start) !== -1; }; } diff --git a/files/fr/web/javascript/reference/global_objects/string/index.md b/files/fr/web/javascript/reference/global_objects/string/index.md index 25a131e70c0eb8..2627dc245992e3 100644 --- a/files/fr/web/javascript/reference/global_objects/string/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/index.md @@ -18,7 +18,7 @@ Il est possible de créer des chaînes de caractères comme des valeurs primitiv ```js const string1 = "Une chaîne de caractères primitive"; -const string2 = 'Là encore une valeur de chaîne de caractères primitive'; +const string2 = "Là encore une valeur de chaîne de caractères primitive"; const string3 = `Et ici aussi`; ``` @@ -35,13 +35,13 @@ Les valeurs littérales pour les chaînes de caractères peuvent être indiquée Il existe deux façons d'accéder à un caractère dans une chaîne. La première façon consiste à utiliser la méthode [`charAt()`](/fr/docs/Web/JavaScript/Reference/Global_Objects/String/charAt) : ```js -return 'chat'.charAt(2); // renvoie "a" +return "chat".charAt(2); // renvoie "a" ``` La seconde méthode, introduite avec ECMAScript 5, est de manipuler la chaîne comme un tableau, où les caractères sont les éléments du tableau et ont un indice correspondant à leur position : ```js -return 'chat'[2]; // renvoie "a" +return "chat"[2]; // renvoie "a" ``` En utilisant la seconde notation, il est impossible de supprimer ou d'affecter une valeur à ces propriétés. En effet, les propriétés concernées ne sont ni accessibles en écriture ni configurables. Pour plus d'informations, voir la page de [`Object.defineProperty()`](/fr/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty). @@ -53,7 +53,8 @@ Les développeurs C utilisent la fonction `strcmp()` pour comparer des chaînes ```js let a = "a"; let b = "b"; -if (a < b) { // true +if (a < b) { + // true console.log(a + " est inférieure à " + b); } else if (a > b) { console.log(a + " est supérieure à " + b); @@ -68,7 +69,7 @@ On notera que `a == b` compare les chaînes de caractères `a` et `b` de façon ```js function isEqual(str1, str2) { - return str1.toUpperCase() === str2.toUpperCase() + return str1.toUpperCase() === str2.toUpperCase(); } ``` @@ -85,16 +86,16 @@ let s_prim = "toto"; let s_obj = new String(s_prim); console.log(typeof s_prim); // affiche "string" -console.log(typeof s_obj); // affiche "object" +console.log(typeof s_obj); // affiche "object" ``` Les chaînes primitives et les objets `String` renvoient des résultats différents lorsqu'ils sont évalués avec [`eval()`](/fr/docs/Web/JavaScript/Reference/Global_Objects/eval). Les chaînes primitives sont traitées comme du code source, tandis que les objets `String` sont traités comme tous les autres objets, en renvoyant l'objet. Par exemple : ```js -let s1 = "2 + 2"; // crée une chaîne primitive -let s2 = new String("2 + 2"); // crée un objet String -console.log(eval(s1)); // renvoie le nombre 4 -console.log(eval(s2)); // renvoie la chaîne "2 + 2" +let s1 = "2 + 2"; // crée une chaîne primitive +let s2 = new String("2 + 2"); // crée un objet String +console.log(eval(s1)); // renvoie le nombre 4 +console.log(eval(s2)); // renvoie la chaîne "2 + 2" ``` Pour ces raisons, il peut y avoir certains problèmes quand le code attend une chaîne primitive plutôt qu'un objet `String`. Toutefois, cette distinction est rarement nécessaire en pratique. @@ -132,9 +133,10 @@ Il peut arriver que le code contienne des chaînes plutôt longues. Plutôt que #### Méthode 1 ```js -let chaineLongue = "Voici une très longue chaîne qui a besoin " + - " d'être passée à la ligne parce que sinon " + - " ça risque de devenir illisible."; +let chaineLongue = + "Voici une très longue chaîne qui a besoin " + + " d'être passée à la ligne parce que sinon " + + " ça risque de devenir illisible."; ``` #### Méthode 2 @@ -142,7 +144,8 @@ let chaineLongue = "Voici une très longue chaîne qui a besoin " + On peut sinon utiliser le caractère barre oblique inversée "\\" à la fin de chaque ligne pour indiquer que la chaîne continue sur la ligne suivante. Il faut bien faire attention à ce que la barre oblique soit bien le dernier caractère de la ligne avant le saut de ligne. Sinon, cela ne fonctionnera pas. Voilà comment se présente cette forme : ```js -let chaineLongue = "Voici une très longue chaîne qui a besoin \ +let chaineLongue = + "Voici une très longue chaîne qui a besoin \ d'être passée à la ligne parce que sinon \ ça risque de devenir illisible."; ``` @@ -294,7 +297,7 @@ d'être passée à la ligne parce que sinon Il est possible d'utiliser `String` comme une alternative à [`toString()`](/fr/docs/Web/JavaScript/Reference/Global_Objects/String/toString) car cela permet de traiter les valeurs [`null`](/fr/docs/Web/JavaScript/Reference/Global_Objects/null), [`undefined`](/fr/docs/Web/JavaScript/Reference/Global_Objects/undefined) et les [symboles](/fr/docs/Web/JavaScript/Reference/Global_Objects/Symbol). Ainsi : ```js -let chainesSortie = [] +let chainesSortie = []; for (let i = 0, n = valeursEntree.length; i < n; ++i) { chainesSortie.push(String(valeursEntree[i])); } diff --git a/files/fr/web/javascript/reference/global_objects/string/indexof/index.md b/files/fr/web/javascript/reference/global_objects/string/indexof/index.md index aa9c5ae830e164..18b7f85c444515 100644 --- a/files/fr/web/javascript/reference/global_objects/string/indexof/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/indexof/index.md @@ -15,8 +15,8 @@ La méthode **`indexOf()`** renvoie l'indice de la première occurence de la val ## Syntaxe ```js -str.indexOf(valeurRecherchée) -str.indexOf(valeurRecherchée, indexDébut) +str.indexOf(valeurRecherchée); +str.indexOf(valeurRecherchée, indexDébut); ``` ### Paramètres @@ -35,14 +35,14 @@ L'indice de la première occurrence de la valeur indiquée, `-1` si elle n'est p Les caractères dans une chaîne de caractères sont indexés de la gauche à la droite. L'indice du premier caractère est 0, celui du dernier caractère (d'une chaîne `str`) est `str.length - 1.` ```js -"Blue Whale".indexOf("Blue"); // retourne 0 -"Blue Whale".indexOf("Blute"); // retourne -1 +"Blue Whale".indexOf("Blue"); // retourne 0 +"Blue Whale".indexOf("Blute"); // retourne -1 "Blue Whale".indexOf("Whale", 0); // retourne 5 "Blue Whale".indexOf("Whale", 5); // retourne 5 -"Blue Whale".indexOf(""); // retourne 0 -"Blue Whale".indexOf("", 9); // retourne 9 -"Blue Whale".indexOf("", 10); // retourne 10 -"Blue Whale".indexOf("", 11); // retourne 10 +"Blue Whale".indexOf(""); // retourne 0 +"Blue Whale".indexOf("", 9); // retourne 9 +"Blue Whale".indexOf("", 10); // retourne 10 +"Blue Whale".indexOf("", 11); // retourne 10 ``` ### Sensibilité à la casse @@ -50,7 +50,7 @@ Les caractères dans une chaîne de caractères sont indexés de la gauche à la La méthode `indexOf()` est sensible à la casse. Par exemple, l'expression suivante retourne -1 : ```js -"Blue Whale".indexOf("blue") // retourne -1 +"Blue Whale".indexOf("blue"); // retourne -1 ``` Attention : `0` n'est pas une valeur qui peut être évaluée à `true` et `-1` n'est pas une valeur qui peut être évaluée à `false`. Ainsi, si on souhaite tester si une chaîne de caractères existe au sein d'une autre chaîne de caractères, on procèdera de cette façon (ou on utilisera {{jsxref("String.prototype.includes()")}} @@ -67,7 +67,7 @@ Attention : `0` n'est pas une valeur qui peut être évaluée à `true` et `-1` L'exemple suivant utilise `indexOf()` et `lastIndexOf()` pour localiser différentes valeurs dans la chaîne de caractères "`Brave new world`". ```js -const uneChaîne = "Brave new world" +const uneChaîne = "Brave new world"; console.log("Indice du premier w " + uneChaîne.indexOf("w")); // Affiche 8 @@ -88,9 +88,12 @@ L'exemple suivant définit 2 chaînes de caractères. Ces variables contiennent const maChaîne = "brie, reblochon, cheddar"; const maChaîneMajuscules = "Brie, Reblochon, Cheddar"; -console.log('maChaîne.indexOf("cheddar") is '+ maChaîne.indexOf("cheddar")); +console.log('maChaîne.indexOf("cheddar") is ' + maChaîne.indexOf("cheddar")); // Affiche 19 -console.log('maChaîneMajuscules.indexOf("cheddar") is ' + maChaîneMajuscules.indexOf("cheddar")); +console.log( + 'maChaîneMajuscules.indexOf("cheddar") is ' + + maChaîneMajuscules.indexOf("cheddar"), +); // Affiche -1 ``` @@ -103,9 +106,9 @@ const str = "Chaîne x de test x"; let count = 0; let pos = str.indexOf("x"); -while ( pos != -1 ) { - count++; - pos = str.indexOf( "x",pos + 1 ); +while (pos != -1) { + count++; + pos = str.indexOf("x", pos + 1); } console.log(count); // Affiche 2 ``` diff --git a/files/fr/web/javascript/reference/global_objects/string/italics/index.md b/files/fr/web/javascript/reference/global_objects/string/italics/index.md index 0fc4cdeaefdc0c..2f4a9a03f19e35 100644 --- a/files/fr/web/javascript/reference/global_objects/string/italics/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/italics/index.md @@ -11,7 +11,7 @@ La méthode **`italics()`** permet de créer un élément HTML {{HTMLElement("i" ## Syntaxe ```js -str.italics() +str.italics(); ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/string/lastindexof/index.md b/files/fr/web/javascript/reference/global_objects/string/lastindexof/index.md index 089e606932985e..bb2968a328029e 100644 --- a/files/fr/web/javascript/reference/global_objects/string/lastindexof/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/lastindexof/index.md @@ -32,14 +32,14 @@ L'indice de la dernière occurrence de la valeur indiquée, `-1` si elle n'est p Les caractères d'une chaîne de caractères sont indexés de gauche à droite. L'indice du premier caractère vaut 0 et l'indice du dernier caractère vaut `maChaîne.length - 1`. ```js -'canal'.lastIndexOf('a'); // renvoie 3 -'canal'.lastIndexOf('a', 2); // renvoie 1 -'canal'.lastIndexOf('a', 0); // renvoie -1 -'canal'.lastIndexOf('x'); // renvoie -1 -'canal'.lastIndexOf('c', -5); // renvoie 0 -'canal'.lastIndexOf('c', 0); // renvoie 0 -'canal'.lastIndexOf(''); // renvoie 5 -'canal'.lastIndexOf('', 2); // renvoie 2 +"canal".lastIndexOf("a"); // renvoie 3 +"canal".lastIndexOf("a", 2); // renvoie 1 +"canal".lastIndexOf("a", 0); // renvoie -1 +"canal".lastIndexOf("x"); // renvoie -1 +"canal".lastIndexOf("c", -5); // renvoie 0 +"canal".lastIndexOf("c", 0); // renvoie 0 +"canal".lastIndexOf(""); // renvoie 5 +"canal".lastIndexOf("", 2); // renvoie 2 ``` > **Note :** `'abab'.lastIndexOf('ab', 2)` renvoie `2` et pas `0` car l'argument `indiceDébut` ne limite que le début de la correspondance recherchée ( qui est `'ab'`) @@ -49,7 +49,7 @@ Les caractères d'une chaîne de caractères sont indexés de gauche à droite. La méthode `lastIndexOf()` est sensible à la casse (une lettre en minuscule (i) est différente d'une lettre en majuscule (I)). Ainsi, le résultat de l'expression suivante sera -1 : ```js -'Blue Whale, Killer Whale'.lastIndexOf('blue'); // renvoie -1 +"Blue Whale, Killer Whale".lastIndexOf("blue"); // renvoie -1 ``` ## Exemples @@ -57,16 +57,16 @@ La méthode `lastIndexOf()` est sensible à la casse (une lettre en minuscule (i Dans l'exemple suivant, on utilise {{jsxref("String.prototype.indexOf()", "indexOf()")}} et `lastIndexOf()` pour situer certaines valeurs dans la chaîne `"Brave new world"`. ```js -var maChaîne = 'Brave new world'; +var maChaîne = "Brave new world"; -console.log('Indice du premier w ' + maChaîne.indexOf('w')); +console.log("Indice du premier w " + maChaîne.indexOf("w")); // Affiche 8 -console.log('Indice du dernier w ' + maChaîne.lastIndexOf('w')); +console.log("Indice du dernier w " + maChaîne.lastIndexOf("w")); // Affiche 10 -console.log('Indice du premier "new" ' + maChaîne.indexOf('new')); +console.log('Indice du premier "new" ' + maChaîne.indexOf("new")); // Affiche 6 -console.log('Indice du dernier "new" ' + maChaîne.lastIndexOf('new')); +console.log('Indice du dernier "new" ' + maChaîne.lastIndexOf("new")); // Affiche 6 ``` diff --git a/files/fr/web/javascript/reference/global_objects/string/length/index.md b/files/fr/web/javascript/reference/global_objects/string/length/index.md index dc89601ac698b9..8ddde4b043a3ac 100644 --- a/files/fr/web/javascript/reference/global_objects/string/length/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/length/index.md @@ -13,7 +13,7 @@ La propriété **`length`** représente la longueur d'une chaine de caractères, ## Syntaxe ```js -str.length +str.length; ``` ## Description diff --git a/files/fr/web/javascript/reference/global_objects/string/link/index.md b/files/fr/web/javascript/reference/global_objects/string/link/index.md index ab6447c810b6d1..377d7a48b343b1 100644 --- a/files/fr/web/javascript/reference/global_objects/string/link/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/link/index.md @@ -11,7 +11,7 @@ La méthode **`link()`** permet de créer une chaîne de caractères représenta ## Syntaxe ```js -str.link(url) +str.link(url); ``` ### Paramètres diff --git a/files/fr/web/javascript/reference/global_objects/string/localecompare/index.md b/files/fr/web/javascript/reference/global_objects/string/localecompare/index.md index f18da81ea8a045..d94c6878af9c55 100644 --- a/files/fr/web/javascript/reference/global_objects/string/localecompare/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/localecompare/index.md @@ -15,14 +15,15 @@ Les arguments `locales` et `options` permettent de définir la locale et des opt ## Syntaxe ```js -localeCompare(chaineAComparer) -localeCompare(chaineAComparer, locales) -localeCompare(chaineAComparer, locales, options) +localeCompare(chaineAComparer); +localeCompare(chaineAComparer, locales); +localeCompare(chaineAComparer, locales, options); ``` ### Paramètres - `chaineAComparer` + - : La chaîne avec laquelle on souhaite comparer la chaîne de caractères courante. - `locales` et `options` @@ -77,8 +78,8 @@ L'exemple qui suit illustre les différents cas de figures lors de la comparaiso `localeCompare()` permet de trier un tableau sans tenir compte de la casse : ```js -var items = ['réservé', 'Premier', 'Cliché', 'communiqué', 'café', 'Adieu']; -items.sort((a, b) => a.localeCompare(b, 'fr', {ignorePunctuation: true})); +var items = ["réservé", "Premier", "Cliché", "communiqué", "café", "Adieu"]; +items.sort((a, b) => a.localeCompare(b, "fr", { ignorePunctuation: true })); // ['Adieu', 'café', 'Cliché', 'communiqué', 'Premier', 'réservé'] ``` @@ -91,9 +92,9 @@ Pour vérifier qu'une implémentation implémente ces paramètres, il est possib ```js function localeCompareSupportsLocales() { try { - 'toto'.localeCompare('truc', 'i'); + "toto".localeCompare("truc", "i"); } catch (e) { - return e.name === 'RangeError'; + return e.name === "RangeError"; } return false; } @@ -104,8 +105,8 @@ function localeCompareSupportsLocales() { Les résultats fournis par la méthode `localeCompare()` peuvent varier selon les locales utilisées. Pour spécifier la locale à utiliser pour votre application, utilisez l'argument `locales` (éventuellement en incluant des locales de recours) : ```js -console.log('ä'.localeCompare('z', 'de')); // une valeur négative : en allemand ä est avant z -console.log('ä'.localeCompare('z', 'sv')); // une valeur positive : en suédois, ä arrive après z +console.log("ä".localeCompare("z", "de")); // une valeur négative : en allemand ä est avant z +console.log("ä".localeCompare("z", "sv")); // une valeur positive : en suédois, ä arrive après z ``` ### Utiliser le paramètre `options` @@ -114,10 +115,10 @@ Les résultats construits par la méthode `localeCompare()` peuvent être adapt ```js // en allemand, ä et a ont la même lettre de base -console.log('ä'.localeCompare('a', 'de', {sensitivity: "base"})); // 0 +console.log("ä".localeCompare("a", "de", { sensitivity: "base" })); // 0 // en suédois, ä et a n'ont pas la même lettre de base -console.log('ä'.localeCompare('a', 'sv', {sensitivity: "base"})); // une valeur positive +console.log("ä".localeCompare("a", "sv", { sensitivity: "base" })); // une valeur positive ``` ### Tri numérique @@ -127,10 +128,10 @@ console.log('ä'.localeCompare('a', 'sv', {sensitivity: "base"})); // une valeur console.log("2".localeCompare("10")); // 1 // En utilisant un ordre numérique -console.log("2".localeCompare("10", undefined, {numeric: true})); // -1 +console.log("2".localeCompare("10", undefined, { numeric: true })); // -1 // En utilisant une balise de locale -console.log("2".localeCompare("10","en-u-kn-true")); // -1 +console.log("2".localeCompare("10", "en-u-kn-true")); // -1 ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/string/match/index.md b/files/fr/web/javascript/reference/global_objects/string/match/index.md index 22377f2377c13b..9894bfbdeecf4c 100644 --- a/files/fr/web/javascript/reference/global_objects/string/match/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/match/index.md @@ -13,7 +13,7 @@ La méthode **`match()`** permet d'obtenir le tableau des correspondances entre ## Syntaxe ```js -str.match(regexp) +str.match(regexp); ``` ### Paramètres @@ -53,7 +53,7 @@ Si l'expression n'utilise pas le drapeau (_flag_) `g`, le résultat obtenu sera Dans l'exemple suivant, on utilise `match()` afin de trouver la chaîne `'Chapitre'` suivie par un ou plusieurs chiffres séparés par des points. L'expression utilisée active le drapeau `i` afin que la casse ne soit pas prise en compte. ```js -var str = 'Pour plus d\'informations, voir le chapitre 3.4.5.1'; +var str = "Pour plus d'informations, voir le chapitre 3.4.5.1"; var re = /(chapitre \d+(\.\d)*)/i; var trouvé = str.match(re); @@ -72,7 +72,7 @@ console.log(trouvé); Dans cet exemple, on illustre comment utiliser des drapeaux avec l'expression rationnelle qui est un argument de `match()`. Chaque lettre de A à E et de a à e est renvoyée, chacune dans un élément du tableau de résultat. ```js -var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; +var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; var regexp = /[A-E]/gi; var tableau_correspondances = str.match(regexp); @@ -86,11 +86,11 @@ Lorsque le paramètre passé à la fonction est une chaîne de caractères ou un ```js var str1 = "NaN signifie : qui n'est pas un nombre."; -var str2 = "Mon père a 65 ans." -str1.match("nombre"); // "nombre" est une chaîne, renvoie ["nombre"] -str1.match(NaN); // NaN est de type number, renvoie ["NaN"] -str2.match(65); // Renvoie ["65"] -str2.match(+65); // Renvoie également ["65"] +var str2 = "Mon père a 65 ans."; +str1.match("nombre"); // "nombre" est une chaîne, renvoie ["nombre"] +str1.match(NaN); // NaN est de type number, renvoie ["NaN"] +str2.match(65); // Renvoie ["65"] +str2.match(+65); // Renvoie également ["65"] ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/string/matchall/index.md b/files/fr/web/javascript/reference/global_objects/string/matchall/index.md index 5900da52fde15e..1c9df3b6216aa2 100644 --- a/files/fr/web/javascript/reference/global_objects/string/matchall/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/matchall/index.md @@ -13,7 +13,7 @@ La méthode **`matchAll()`** renvoie un itérateur contenant l'ensemble des corr ## Syntaxe ```js -str.matchAll(regexp) +str.matchAll(regexp); ``` ### Paramètres @@ -32,11 +32,13 @@ Un [itérateur](/fr/docs/Web/JavaScript/Guide/Iterators_and_Generators). Avant l'apparition de `matchAll()` en JavaScript, il était possible d'utiliser {{jsxref("RegExp.exec")}} (et des expressions rationnelles utilisant le marqueur `/g`) dans une boucle afin d'obtenir l'ensemble des correspondances : ```js -const regexp = RegExp('foo*','g'); -const str = 'table football, foosball'; +const regexp = RegExp("foo*", "g"); +const str = "table football, foosball"; while ((matches = regexp.exec(str)) !== null) { - console.log(`${matches[0]} trouvé. Prochaine recherche à partir de ${regexp.lastIndex}.`); + console.log( + `${matches[0]} trouvé. Prochaine recherche à partir de ${regexp.lastIndex}.`, + ); // dans la console : "foo trouvé. Prochaine recherche à partir de 9." // dans la console : "foo trouvé. Prochaine recherche à partir de 19." } @@ -45,8 +47,8 @@ while ((matches = regexp.exec(str)) !== null) { Avec `matchAll()`, on peut éviter la boucle `while` et le marqueur global. On récupère l'itérateur et on utilise une boucle [`for...of`](/fr/docs/Web/JavaScript/Reference/Instructions/for...of), [la décomposition de tableau](/fr/docs/Web/JavaScript/Reference/Opérateurs/Syntaxe_décomposition) ou encore {{jsxref("Array.from()")}} : ```js -const regexp = RegExp('foo*','g'); -const str = 'table football, foosball'; +const regexp = RegExp("foo*", "g"); +const str = "table football, foosball"; let matches = str.matchAll(regexp); for (const match of matches) { @@ -59,7 +61,7 @@ for (const match of matches) { // On rappelle matchAll afin de créer un nouvel itérateur matches = str.matchAll(regexp); -Array.from(matches, m => m[0]); +Array.from(matches, (m) => m[0]); // Array [ "foo", "foo" ] ``` @@ -69,7 +71,7 @@ Un autre avantage de `matchAll()` est un meilleur accès aux groupes capturants. ```js var regexp = /t(e)(st(\d?))/g; -var str = 'test1test2'; +var str = "test1test2"; str.match(regexp); // Array ['test1', 'test2'] diff --git a/files/fr/web/javascript/reference/global_objects/string/normalize/index.md b/files/fr/web/javascript/reference/global_objects/string/normalize/index.md index 62228d5cea2efe..2e928dd7bd6348 100644 --- a/files/fr/web/javascript/reference/global_objects/string/normalize/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/normalize/index.md @@ -49,7 +49,6 @@ La méthode `normalize()` renvoie la forme normalisée Unicode de la chaîne de // U+0323: COMBINING DOT BELOW var str = "\u1E9B\u0323"; - // Forme canonique composée (Canonically-composed form) (NFC) // U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE @@ -57,7 +56,6 @@ var str = "\u1E9B\u0323"; str.normalize("NFC"); // "\u1E9B\u0323" str.normalize(); // la même chaîne que précédemment - // Forme canonique décomposée (Canonically-decomposed form) (NFD) // U+017F: LATIN SMALL LETTER LONG S @@ -65,13 +63,11 @@ str.normalize(); // la même chaîne que précédemment // U+0307: COMBINING DOT ABOVE str.normalize("NFD"); // "\u017F\u0323\u0307" - // Forme composée compatible (NFKC) // U+1E69: LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE str.normalize("NFKC"); // "\u1E69" - // Forme décomposée compatible (NFKD) // U+0073: LATIN SMALL LETTER S diff --git a/files/fr/web/javascript/reference/global_objects/string/padend/index.md b/files/fr/web/javascript/reference/global_objects/string/padend/index.md index 8a4dc3d1478643..a4cfc8cdb596fc 100644 --- a/files/fr/web/javascript/reference/global_objects/string/padend/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/padend/index.md @@ -30,10 +30,10 @@ Une chaîne de caractères ({{jsxref("String")}}) dont la longueur est celle ind ## Exemples ```js -'abc'.padEnd(10); // "abc " -'abc'.padEnd(10, "toto"); // "abctototot" -'abc'.padEnd(6,"123456"); // "abc123" -'abc'.padEnd(1); // "abc" +"abc".padEnd(10); // "abc " +"abc".padEnd(10, "toto"); // "abctototot" +"abc".padEnd(6, "123456"); // "abc123" +"abc".padEnd(1); // "abc" ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/string/padstart/index.md b/files/fr/web/javascript/reference/global_objects/string/padstart/index.md index 5adc6b65983579..b9cf9978aa013a 100644 --- a/files/fr/web/javascript/reference/global_objects/string/padstart/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/padstart/index.md @@ -30,11 +30,11 @@ Une chaîne de caractères ({{jsxref("String")}}) dont la longueur est celle ind ## Exemples ```js -'abc'.padStart(10); // " abc" -'abc'.padStart(10, "toto"); // "totototabc" -'abc'.padStart(6,"123465"); // "123abc" -'abc'.padStart(8, "0"); // "00000abc" -'abc'.padStart(1); // "abc" +"abc".padStart(10); // " abc" +"abc".padStart(10, "toto"); // "totototabc" +"abc".padStart(6, "123465"); // "123abc" +"abc".padStart(8, "0"); // "00000abc" +"abc".padStart(1); // "abc" ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/string/raw/index.md b/files/fr/web/javascript/reference/global_objects/string/raw/index.md index ce6d060803f135..a9c245e6515224 100644 --- a/files/fr/web/javascript/reference/global_objects/string/raw/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/raw/index.md @@ -13,9 +13,9 @@ La méthode statique **`String.raw()`** est une fonction d'étiquetage (_tag fun ## Syntaxe ```js -String.raw(callSite, ...substitutions) +String.raw(callSite, ...substitutions); -String.raw`gabaritChaîne` +String.raw`gabaritChaîne`; ``` ### Paramètres @@ -45,7 +45,7 @@ La méthode `String.raw()` est la seule méthode d'étiquetage native pour les c ## Exemples ```js -String.raw`Hi\n${2+3}!`; +String.raw`Hi\n${2 + 3}!`; // "Hi\n5!", le caractère après "Hi" n'est pas // le caractère de nouvelle ligne // "\" et "n" sont bien deux caractères distincts @@ -66,7 +66,7 @@ String.raw`Hi\n${nom}!`; // Généralement, on n'appelle pas String.raw // comme une fonction, mais c'est possible : -String.raw({raw: "test"}, 0, 1, 2); +String.raw({ raw: "test" }, 0, 1, 2); // "t0e1s2t" ``` diff --git a/files/fr/web/javascript/reference/global_objects/string/repeat/index.md b/files/fr/web/javascript/reference/global_objects/string/repeat/index.md index f95f06af52d0e4..4e14cee9564dad 100644 --- a/files/fr/web/javascript/reference/global_objects/string/repeat/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/repeat/index.md @@ -13,7 +13,7 @@ La méthode **`repeat()`** construit et renvoie une nouvelle chaine de caractèr ## Syntaxe ```js -str.repeat(compte) +str.repeat(compte); ``` ### Paramètres @@ -38,14 +38,19 @@ Une nouvelle chaîne de caractères composée du nombre indiqué de copies de la ## Exemples ```js -"abc".repeat(-1) // RangeError -"abc".repeat(0) // "" -"abc".repeat(1) // "abc" -"abc".repeat(2) // "abcabc" -"abc".repeat(3.5) // "abcabcabc" (le compteur est converti en un nombre entier) -"abc".repeat(1/0) // RangeError - -({toString : () => "abc", repeat : String.prototype.repeat}).repeat(2) +"abc".repeat(-1); // RangeError +"abc".repeat(0); // "" +"abc".repeat(1); // "abc" +"abc".repeat(2); // "abcabc" +"abc".repeat(3.5); // "abcabcabc" (le compteur est converti en un nombre entier) +"abc" + .repeat(1 / 0) + ( + // RangeError + + { toString: () => "abc", repeat: String.prototype.repeat }, + ) + .repeat(2); // "abcabc" (repeat() est une méthode générique) ``` diff --git a/files/fr/web/javascript/reference/global_objects/string/replace/index.md b/files/fr/web/javascript/reference/global_objects/string/replace/index.md index 59ae32c73ee0a6..21ee14e662c4c3 100644 --- a/files/fr/web/javascript/reference/global_objects/string/replace/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/replace/index.md @@ -15,7 +15,7 @@ La chaîne de caractère originale reste inchangée. ## Syntaxe ```js -chn.replace(regexp|souschn, nouvSouschn|fonction) +chn.replace(regexp | souschn, nouvSouschn | fonction); ``` ### Paramètres @@ -143,9 +143,12 @@ L'exemple suivant affectera `'abc - 12345 - #$*%'` à la variable `nouvelleChain ```js function remplaceur(correspondance, p1, p2, p3, decalage, chaine) { // p1 est non numérique, p2 numérique, et p3 non-alphanumérique - return [p1, p2, p3].join(' - '); + return [p1, p2, p3].join(" - "); } -var nouvelleChaine = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, remplaceur); +var nouvelleChaine = "abc12345#$*%".replace( + /([^\d]*)(\d*)([^\w]*)/, + remplaceur, +); console.log(nouvelleChaine); // abc - 12345 - #$*% ``` @@ -156,8 +159,8 @@ console.log(nouvelleChaine); // abc - 12345 - #$*% Dans l'exemple suivant, l'expression régulière est définie dans `replace()` et inclut l'indicateur d'indifférence à la casse. ```js -var chn = 'Twas the night before Xmas...'; -var nouvChn = chn.replace(/xmas/i, 'Christmas'); +var chn = "Twas the night before Xmas..."; +var nouvChn = chn.replace(/xmas/i, "Christmas"); console.log(nouvChn); // Twas the night before Christmas... ``` @@ -171,8 +174,8 @@ Le remplacement global ne peut être fait qu'avec une expression régulière. Da ```js var re = /pommes/gi; -var chn = 'Les pommes sont rondes, et les pommes sont juteuses.'; -var nouvChn = chn.replace(re, 'oranges'); +var chn = "Les pommes sont rondes, et les pommes sont juteuses."; +var nouvChn = chn.replace(re, "oranges"); console.log(nouvChn); // Les oranges sont rondes, et les oranges sont juteuses. ``` @@ -184,7 +187,7 @@ Le script suivant intervertit les mots dans la chaîne de caractères. Pour le t ```js var re = /(\w+)\s(\w+)/; -var chn = 'Jean Martin'; +var chn = "Jean Martin"; var nouvChn = chn.replace(re, "$2, $1"); console.log(nouvChn); // Martin, Jean ``` @@ -200,7 +203,7 @@ La fonction de remplacement accepte le fragment en correspondance comme paramèt ```js function styleFormatTiret(nomPropriete) { function majusculesEnTiretMinuscules(correspondance, decalage, chaine) { - return (decalage > 0 ? '-' : '') + correspondance.toLowerCase(); + return (decalage > 0 ? "-" : "") + correspondance.toLowerCase(); } return nomPropriete.replace(/[A-Z]/g, majusculesEnTiretMinuscules); } @@ -211,7 +214,7 @@ Avec `styleFormatTiret('borderTop')`, cela renvoie 'border-top'. Du fait que nous voulons transformer davantage le résultat de la correspondance avant la substitution finale, nous devons utiliser une fonction. Cela force l'évaluation de la correspondance avant la méthode {{jsxref ("String.prototype.toLowerCase()", "toLowerCase()")}}. Si nous avions essayé de le faire en utilisant la correspondance sans fonction, le {{jsxref ("String.prototype.toLowerCase()", "toLowerCase()")}} n'aurait eu aucun effet. ```js -var nouvChn = nomPropriete.replace(/[A-Z]/g, '-' + '$&'.toLowerCase()); // ne fonctionne pas +var nouvChn = nomPropriete.replace(/[A-Z]/g, "-" + "$&".toLowerCase()); // ne fonctionne pas ``` Ceci est dû au fait que `'$&'.toLowerCase()` serait d'abord évalué comme un littéral de chaîne (résultant en le même `'$&'`) avant d'utiliser les caractères comme modèle. @@ -225,7 +228,7 @@ L'expression régulière `test` vérifie tout nombre se terminant par F. Le nomb ```js function f2c(x) { function convertir(chn, p1, decalage, s) { - return ((p1-32) * 5/9) + 'C'; + return ((p1 - 32) * 5) / 9 + "C"; } var s = String(x); var test = /(-?\d+(?:\.\d*)?)F\b/g; @@ -241,7 +244,7 @@ L'exemple suivant accepte un modèle chaîne et le convertit en un tableau d'obj Une chaîne de caractères composée des caractères `x`, `-` et `_` -```js +```plain x-x_ x---x---x---x--- @@ -251,7 +254,7 @@ x_x_x___x___x___ **Sortie :**Un tableau d'objets. Un `'x'` dénote un état `'marche'`, un `'-'` symbolise un état '`arret`' et un `'_'` (blanc souligné) symbolise la longueur d'un état `'marche'`. -```json +```js [ { marche: true, longueur: 1 }, { marche: false, longueur: 1 }, @@ -263,11 +266,11 @@ x_x_x___x___x___ **Fragment :** ```js -var chn = 'x-x_'; +var chn = "x-x_"; var tabRet = []; -chn.replace(/(x_*)|(-)/g, function(correspondance, $1, $2){ - if($1) tabRet.push({ marche: true, longueur: $1.length }); - if($2) tabRet.push({ marche: false, longueur: 1 }); +chn.replace(/(x_*)|(-)/g, function (correspondance, $1, $2) { + if ($1) tabRet.push({ marche: true, longueur: $1.length }); + if ($2) tabRet.push({ marche: false, longueur: 1 }); }); console.log(tabRet); diff --git a/files/fr/web/javascript/reference/global_objects/string/replaceall/index.md b/files/fr/web/javascript/reference/global_objects/string/replaceall/index.md index 0ea4d226b50e9d..297900b5f75894 100644 --- a/files/fr/web/javascript/reference/global_objects/string/replaceall/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/replaceall/index.md @@ -112,7 +112,7 @@ Le nombre d'arguments exact dépend du premier argument de `replaceAll()` : si c ### Utiliser replaceAll() ```js -'aabbcc'.replaceAll('b', '.'); +"aabbcc".replaceAll("b", "."); // 'aa..cc' ``` @@ -128,8 +128,8 @@ TypeError: replaceAll must be called with a global RegExp L'exemple suivant, utilisant le marqueur `g`, fonctionnera : ```js example-good -'aabbcc'.replaceAll(/b/g, '.'); -"aa..cc" +"aabbcc".replaceAll(/b/g, "."); +("aa..cc"); ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/string/search/index.md b/files/fr/web/javascript/reference/global_objects/string/search/index.md index 26c3940b8c986b..83222587624838 100644 --- a/files/fr/web/javascript/reference/global_objects/string/search/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/search/index.md @@ -13,7 +13,7 @@ La méthode **`search()`** éxecute une recherche dans une chaine de caractères ## Syntaxe ```js -str.search(regexp) +str.search(regexp); ``` ### Paramètres diff --git a/files/fr/web/javascript/reference/global_objects/string/slice/index.md b/files/fr/web/javascript/reference/global_objects/string/slice/index.md index 0ee0886fb67f5e..db649bc739f644 100644 --- a/files/fr/web/javascript/reference/global_objects/string/slice/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/slice/index.md @@ -42,11 +42,11 @@ Par exemple, `chn.slice(2, -1)` extrait du troisième caractère jusqu'à l'avan L'exemple suivant utilise `slice()` pour créer une nouvelle chaîne de caractères. ```js -var chn1 = 'Le matin est sur nous.', // la longueur de chn1 est de 22 - chn2 = chn1.slice(1, 8), - chn3 = chn1.slice(3, -2), - chn4 = chn1.slice(13), - chn5 = chn1.slice(30); +var chn1 = "Le matin est sur nous.", // la longueur de chn1 est de 22 + chn2 = chn1.slice(1, 8), + chn3 = chn1.slice(3, -2), + chn4 = chn1.slice(13), + chn5 = chn1.slice(30); console.log(chn2); // SORTIE : e matin console.log(chn3); // SORTIE : matin est sur nou console.log(chn4); // SORTIE : sur nous. @@ -58,10 +58,10 @@ console.log(chn5); // SORTIE : "" L'exemple suivant utilise `slice()` avec des indices négatifs. ```js -var chn = 'Le matin est sur nous.'; -chn.slice(-3); // retourne "us." +var chn = "Le matin est sur nous."; +chn.slice(-3); // retourne "us." chn.slice(-3, -1); // retourne "us" -chn.slice(0, -1); // retourne "Le matin est sur nous" +chn.slice(0, -1); // retourne "Le matin est sur nous" ``` Dans l'exemple qui suit, on commence à chercher l'indice de début à partir de la fin de la chaîne avec l'argument `-11` et on utilise un indice de fin positif avec `16` : diff --git a/files/fr/web/javascript/reference/global_objects/string/small/index.md b/files/fr/web/javascript/reference/global_objects/string/small/index.md index f5d16dfd285e40..aeca3046f5cc0c 100644 --- a/files/fr/web/javascript/reference/global_objects/string/small/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/small/index.md @@ -11,7 +11,7 @@ La méthode **`small()`** permet de créer un élément HTML {{HTMLElement("smal ## Syntaxe ```js -str.small() +str.small(); ``` ### Valeur de retour @@ -32,15 +32,15 @@ L'exemple suivant illustre les différentes méthodes de `String` permettant de ```js var worldString = "Coucou monde"; -console.log(worldString.small()); // Coucou monde -console.log(worldString.big()); // Coucou monde +console.log(worldString.small()); // Coucou monde +console.log(worldString.big()); // Coucou monde console.log(worldString.fontsize(7)); // Coucou monde ``` L'objet {{domxref("HTMLElement.style", "element.style")}} permet d'utiliser l'attribut `style` de l'élément et de le manipuler de façon générique. Par exemple : ```js -document.getElementById('IDélément').style.fontSize = '0.7em' +document.getElementById("IDélément").style.fontSize = "0.7em"; ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/string/split/index.md b/files/fr/web/javascript/reference/global_objects/string/split/index.md index 357d43232ddf4c..8c5bb11e86ef12 100644 --- a/files/fr/web/javascript/reference/global_objects/string/split/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/split/index.md @@ -56,10 +56,10 @@ Si le séparateur est un tableau, alors ce tableau est converti en une chaîne d Lorsque la chaîne de caractères est vide, `split()` retourne un tableau contenant une chaîne de caractères vide, plutôt qu'un tableau vide. Si la chaîne et le séparateur sont tous deux des chaînes vides, un tableau vide est retourné. ```js -const myString = '' -const splits = myString.split() +const myString = ""; +const splits = myString.split(); -console.log(splits) +console.log(splits); // ↪ [""] ``` @@ -72,7 +72,10 @@ function splitString(stringToSplit, separator) { console.log(`La chaine d'origine est : ${stringToSplit}`); console.log(`Le délimiteur est : ${separator}`); - console.log(`Le tableau comporte ${arrayOfStrings.length} elements : `, arrayOfStrings.join(' / ')); + console.log( + `Le tableau comporte ${arrayOfStrings.length} elements : `, + arrayOfStrings.join(" / "), + ); } var tempestString = "Oh brave new world that has such people in it."; @@ -138,7 +141,7 @@ console.log(splits); Ce script affichera : ```js -["Hello", "World.", "How"] +["Hello", "World.", "How"]; ``` ### Découper une expression rationnelle - Parenthèses capturantes @@ -155,7 +158,7 @@ console.log(splits); Ce script affichera : ```js -[ "Hello ", "1", " word. Sentence number ", "2", "." ] +["Hello ", "1", " word. Sentence number ", "2", "."]; ``` > **Note :** `\d` correspond à la [classe de caractères](/fr/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes) pour les chiffres compris entre 0 et 9. @@ -165,8 +168,8 @@ Ce script affichera : > **Attention :** Ce n'est pas une façon robuste d'inverser une chaîne : > > ```js example-bad -> const str = 'asdfghjkl' -> const strReverse = str.split('').reverse().join('') +> const str = "asdfghjkl"; +> const strReverse = str.split("").reverse().join(""); > // 'lkjhgfdsa' > > // split() retourne un tableau sur lequel reverse() et join() peuvent être appliqués. @@ -175,8 +178,8 @@ Ce script affichera : > Cela ne fonctionne pas si la chaîne de caractères contient des groupes de graphèmes, même en utilisant une division sensible aux unicodes. (Utilisez, par exemple, [esrever](https://github.com/mathiasbynens/esrever) à la place). > > ```js example-bad -> const str = 'résumé' -> const strReverse = str.split(/(?:)/u).reverse().join('') +> const str = "résumé"; +> const strReverse = str.split(/(?:)/u).reverse().join(""); > // => "́emuśer" > ``` > diff --git a/files/fr/web/javascript/reference/global_objects/string/startswith/index.md b/files/fr/web/javascript/reference/global_objects/string/startswith/index.md index bf9da05e741c36..cee082815a52c5 100644 --- a/files/fr/web/javascript/reference/global_objects/string/startswith/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/startswith/index.md @@ -36,8 +36,8 @@ Cette méthode permet de savoir si une chaine de caractères commence avec une a ```js var str = "Être, ou ne pas être : telle est la question."; -console.log(str.startsWith("Être")); // true -console.log(str.startsWith("pas être")); // false +console.log(str.startsWith("Être")); // true +console.log(str.startsWith("pas être")); // false console.log(str.startsWith("pas être", 12)); // true ``` diff --git a/files/fr/web/javascript/reference/global_objects/string/strike/index.md b/files/fr/web/javascript/reference/global_objects/string/strike/index.md index 2b3def1b6ee29a..ff46454dcc2563 100644 --- a/files/fr/web/javascript/reference/global_objects/string/strike/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/strike/index.md @@ -11,7 +11,7 @@ La méthode **`strike()`** permet de créer un élément HTML {{HTMLElement("str ## Syntaxe ```js -str.strike() +str.strike(); ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/string/string/index.md b/files/fr/web/javascript/reference/global_objects/string/string/index.md index 9afb06910f0d64..9f3d7a01e07c17 100644 --- a/files/fr/web/javascript/reference/global_objects/string/string/index.md +++ b/files/fr/web/javascript/reference/global_objects/string/string/index.md @@ -11,8 +11,8 @@ Le constructeur **`String`** est utilisé afin de créer un nouvel objet [`Strin ## Syntaxe ```js -new String(truc) -String(truc) +new String(truc); +String(truc); ``` ### Paramètres @@ -27,8 +27,8 @@ String(truc) Selon qu'on utilise `String()` comme une fonction ou comme un constructeur, cela produira différents résultats : ```js -typeof String('Coucou monde'); // string -typeof new String('Coucou monde'); // object +typeof String("Coucou monde"); // string +typeof new String("Coucou monde"); // object ``` Ici, la fonction produit une chaîne de caractères (une valeur primitive). Toutefois, le constructeur produit une instance objet de `String`.