How to Remove Whitespace from Start/Beginning of String in JavaScript?

19-Apr-2023

.

Admin

How to Remove Whitespace from Start/Beginning of String in JavaScript?

This simple article demonstrates of How to Remove Whitespace from Start/Beginning of String in JavaScript. We will use How to remove the white space at the start of the string. you can see JavaScript Remove Whitespace from Start/Beginning of String. this example will help you JavaScript: Remove whitespace from Beginning (Start) and End of String.

You can remove whitespace from the start or beginning of a string in JavaScript using the trim() method. Here's an example:

Example 1:


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Remove Whitespace from Start/Beginning of String in JavaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

let str = " Hello World";

str = str.trim();

console.log(str); // "Hello World"

</script>

</html>

The trim() method removes whitespace from both the start and end of a string. If you only want to remove whitespace from the start, you can use the replace() method with a regular expression like this:

Example 2:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Remove Whitespace from Start/Beginning of String in JavaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

let str = " Hello World";

str = str.replace(/^\s+/, "");

console.log(str); // "Hello World"

</script>

</html>

The regular expression /^\s+/ matches one or more whitespace characters at the beginning of the string. The replace() method replaces this match with an empty string, effectively removing the whitespace from the start of the string.

#JavaScript