Sometimes you have a situation when you are comparing string or doing any opearation, but it returns as expected. This is because the string contains whitespace either beginning or ending of the string. This happens in case you have copied string with whitespace.
let earth = ' Hello earth, how are you? ';
So in this situation, if your string variable mostly from copy-pasted from another source, then it is advised that you remove whitespace from beginning or end of the string.
In this article, we will describe the techniques that you can use to remove whitespace from starting or ending of the string.
trim method removes whitespace from the both side of the string.
let earth = ' Hello earth, how are you? ';
console.log(earth.trim()); // Hello earth, how are you?
trimStart() method removes whitespace from the starting of the string.
let earth = ' Hello earth, how are you? ';
console.log(earth.trimStart()); // Hello earth, how are you?
trimEnd() method removes whitespace from the end of the string.
Example:
let earth = ' Hello earth, how are you? ';
console.log(earth.trimEnd()); // Hello earth, how are you?
If you want to use regular expression, this is also good way to remove string.
Example:
let earth = ' Hello earth, how are you? ';
earth = earth.replace(/(^\s+|\s+$)/g, '');
console.log(earth); // Hello earth, how are you?
I hope it will help you.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
Auto update div content while typing in textarea using jQuery
Use the jQuery keyup() method You can...Send Email with Laravel and SendGrid
Recently while working on Laravel mail f...Laravel - How to Get .env Variable in Blade and Controller?
In this example, you will learn how to a...Client does not support authentication protocol requested by server; consider upgrading MySQL client
Recently I was working on Node.js applic...How to Generate a Timestamp in JavaScript
Use the Date.now() Method You can sim...