Remplace with regExp


html"<div> <h1> {{question}} </h1> 
<ul>
    <li>{{choice1}}</li>
    <li>{{choice2}}</li>
    <li>{{choice3}}</li>
    <li>{{choice4}}</li>
</ul>     
</div>"
randomChoise
 2
newCode"<div> <h1> {{question}} </h1> 
<ul>
    <li>{{choice1}}</li>
    <li class='selected'>{{choice2}}</li>
    <li>{{choice3}}</li>
    <li>{{choice4}}</li>
</ul>     
</div>"
const html = `<div> <h1> {{question}} </h1>
<ul>
<li>{{choice1}}</li>
<li>{{choice2}}</li>
<li>{{choice3}}</li>
<li>{{choice4}}</li>
</ul>
</div>`;
const randomChoise = (html, tagName, pos) => {
const regExp = new RegExp(`<${tagName}`, 'g');
let nbMatch = 0;
let newHTML = html.replace(regExp, function (match) {
if (nbMatch++ == pos) {
return `${match} class='selected'`
} else {
return match;
}
})
return newHTML;
}
const newCode = randomChoise(html, 'li', 2);
console.log(newCode)
view raw remplace.js hosted with ❤ by GitHub

Jest test

  https://github.com/dupontdenis/Jest-test1.git


test("Cat Boisson should has 2 articles", ()=> {
    expect(nbArtByCat.Boisson).toBe(2);
})

test("nb of Cats should be 5", ()=>{
    expect(Object.entries(nbArtByCat).length).toBe(5);
})

localstorage

 localStorage.setItem("saveTab",[1,2,3])

console.log(localStorage.getItem("saveTab")
> 1,2,3

Il faut utiliser JSON

localStorage.setItem("saveTAB",JSON.stringify([1,2,3]))


console.log(localStorage.getItem("saveTAB"))
> [1,2,3] // ce n'est pas un tableau mais un string

typeof localStorage.getItem("saveTAB")

> 'string'

Il faut utiliser JSON.parse
console.log(JSON.parse(localStorage.getItem("saveTAB")))
VM1856:1 (3) [1, 2, 3]
0: 1
1: 2
2: 3
length: 3[[Prototype]]: Array(0)

typeof JSON.parse(localStorage.getItem("saveTAB"))

'object'


En action
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="random-words.js" defer></script>
</head>
<body>
<h1>random word</h1>
<ul id="list"></ul>
</body>
</html>
view raw index.html hosted with ❤ by GitHub
//UI
const list = document.getElementById('list');
//random words
const load = async () => {
const sortable = JSON.parse(localStorage.getItem("words"))
if (!sortable) {
const data = await fetch("https://random-word-api.herokuapp.com/word?number=20");
const words = await data.json();
const alphabetical = words.reduce((a, x) => {
if (!a[x[0]]) a[x[0]] = [];
a[x[0]].push(x);
return a;
}, {});
// console.log(alphabetical)
const sortable = Object.fromEntries(
Object.entries(alphabetical).sort(([a,], [b,]) => {
if (a > b) {
return -1
} else {
return 1
}
})
);
localStorage.setItem("words", JSON.stringify(sortable));
return sortable;
} else {
return sortable;
}
}
// UI
(async () => {
const words = await load();
Object.entries(words).forEach(([letter, words]) => {
// console.log(letter, words)
const tempLi = document.createElement('li')
, tempUl = document.createElement('ul');
words.forEach((word) => tempUl.insertAdjacentHTML('afterbegin', `<li> ${word} </li>`))
tempLi.insertAdjacentElement('beforeend', tempUl)
.insertAdjacentText('beforebegin', `${letter}`)
document
.querySelector("#list")
.insertAdjacentElement('afterbegin', tempLi)
})
})()
view raw random-words.js hosted with ❤ by GitHub

RegExp

 RegExp: \d(?=(\d{3})+\.)

Un nombre suivi de 3 nombres (une ou plusieurs fois) et un point sans les consommer (?= ).

Remplacement: $& 

Correspond au chiffre \d qui correspond.

Match 10-11
Group 14-7332
Match 23-45
Group 14-7332


https://regex101.com/r/wwpOnj/1

random word

 https://random-word-api.herokuapp.com/word?number=3&length=-1


learn API 

 https://random-word-api.herokuapp.com

En action

function import

Voici une importation conditionnel à un click grâce à la fonction : 
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="module" defer src="./script.js"></script>
</head>
<body>
click and see the console
</body>
</html>
view raw index.html hosted with ❤ by GitHub
export default function printModule(){
console.log("from module")
}
export function cl(){
console.log("top")
}
view raw module.js hosted with ❤ by GitHub
document.addEventListener("click", async () => {
const {default: printModule, cl } = await import("./module.js");
printModule();
cl();
console.log("from script")
});
view raw script.js hosted with ❤ by GitHub
import("./module.js");