Demo: JavaScript String Operations
Demo: JavaScript Table Operations
part1.js
const squareNumber = (n) => {
const square = Math.pow(n, 2);
console.log(`The square of ${n} is ${square}.`);
return square;
}
const fixStart = (str) => {
const first = str.charAt(0);
return first + str.slice(1).replaceAll(first, '*');
}
const notBad = (str) => str.replace(/not.*bad/g, "good");
const handleStringOperation = (elementId, func) => {
const inputEl = document.getElementById(elementId);
const outputEl = document.querySelector(`output[for=${elementId}]`);
if (inputEl.value && outputEl) {
outputEl.innerText = func(inputEl.value);
}
}
part1.html
<form id="part1-demo">
<p>
<label for="squareNumberInput">Enter a number to square:</label>
<input id="squareNumberInput" type="number">
<button type="button" class="button button-submit" onclick="handleStringOperation('squareNumberInput', squareNumber)">Check</button>
<output for="squareNumberInput"></output>
</p>
<p>
<label>Check repeating letters:<br></label>
<input id="fixStartInput" type="text" list="fixStartList">
<button type="button" class="button button-submit" onclick="handleStringOperation('fixStartInput', fixStart)">Check</button>
<output for="fixStartInput"></output>
<datalist id="fixStartList">
<option value="babble"></option>
<option value="caca"></option>
<option value="\[^x]\<script>alert('XSS!');"></option>
</datalist>
</p>
<p>
<label>Bad/not bad checker:</label>
<input id="notBadInput" type="text" list="notBadList">
<button type="button" class="button button-submit" onclick="handleStringOperation('notBadInput', notBad)">Check</button>
<output for="notBadInput"></output>
<datalist id="notBadList">
<option value="This not bad cake is okay.">
<option value="This cake is not bad!">
<option value="This movie is not quite so bad!">
</datalist>
</p>
</form>