20-Apr-2023
.
Admin
This article goes in detailed on Remove whitespaces inside a string in javascript. In this article, we will implement a Remove Whitespace from End of String JavaScript. This article goes in detailed on Javascript remove whitespace from beginning and end of string. you can see How can I remove extra white space in a string in javascript.
There are multiple ways to remove whitespace from the end of a string in JavaScript:
1. Using trim() method: The trim() method removes whitespace from both ends of a string.
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 End of String in JavaScript? - NiceSnippets.Com</title>
</head>
<body>
</body>
<script type="text/javascript">
let str = " Hello World! ";
str = str.trim(); // "Hello World!"
</script>
</html>
2. Using replace() method with regular expression: The replace() method replaces all occurrences of a specified value with another value in a string. We can use a regular expression to match all whitespace characters at the end of the string and replace them with an empty string.
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 End of String in JavaScript? - NiceSnippets.Com</title>
</head>
<body>
</body>
<script type="text/javascript">
let str = " Hello World! ";
str = str.replace(/\s+$/g, ""); // " Hello World!"
</script>
</html>
In this example, we used the regular expression /\s+$/g to match one or more whitespace characters (\s+) at the end of the string ($). The g flag is used to perform a global search and replace operation.
3. Using slice() method: We can use the slice() method to remove the whitespace characters from the end of a string by specifying the start and end positions.
Example 3:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How to Remove Whitespace from End of String in JavaScript? - NiceSnippets.Com</title>
</head>
<body>
</body>
<script type="text/javascript">
let str = " Hello World! ";
str = str.slice(0, -1); // " Hello World!"
</script>
</html>
#JavaScript