Use regular expression to remove whitespaces from both sides of a string - Javascript RegExp

Javascript examples for RegExp:Metacharacter

Description

Use regular expression to remove whitespaces from both sides of a string

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Test</button>

<script>
function myTrim(x) {/*from w  w w. j av a2s .co m*/
    return x.replace(/^\s+|\s+$/gm,'');
}

function myFunction() {
    var str = myTrim("        Hello World!        ");
    console.log(str);
}
</script>

</body>
</html>

Related Tutorials