Trim String.trim




' Il trim()metodo rimuove gli spazi bianchi da entrambi i lati di una stringa:


https://www.w3schools.com/js/tryit.asp?filename=tryjs_string_trim

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript String.trim()</h2>

<p>Click the button to alert the string with removed whitespace.</p>

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

<p><strong>Note:</strong> The trim() method is not supported in Internet Explorer 8 and earlier versions.</p>

<script>
function myFunction() {
var str = " Hello World! ";
alert(str.trim());
}
</script>

</body>
</html>


' Se e' necessario supportare IE 8, e' possibile utilizzare replace()invece un'espressione regolare:

' var str = " Hello World! ";

' alert(str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''));



' Puoi anche utilizzare la soluzione di sostituzione sopra per aggiungere una funzione di ritaglio al JavaScript String.prototype:


https://www.w3schools.com/js/tryit.asp?filename=tryjs_string_trim_polyfill

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript String.trim()</h2>

<p>IE 8 does not support String.trim(). To trim a string you can use a polyfill.</p>

<script>
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
};
var str = " Hello World! ";
alert(str.trim());
</script>

</body>
</html>










( trimstringtrim.html )- by Paolo Puglisi - Modifica del 17/12/2023