Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript remove leading and trailing spaces [duplicate]

Here is a test:

console.log(" Golden Katana of the Unflinching Dawn                                    ".replace(/\s+/g,""))

I want to remove the extra spaces at the end of the string but it removes every space in the string, so how could I remove just the extra spaces at the end and just keep Golden Katana of the Unflinching Dawn?

like image 865
wateraura Avatar asked Jul 21 '13 06:07

wateraura


People also ask

How do you remove trailing and leading spaces in JS?

JavaScript String trim() The trim() method removes whitespace from both sides of a string.

How do you remove double spacing in JavaScript?

Use JavaScript's string. replace() method with a regular expression to remove extra spaces. The dedicated RegEx to match any whitespace character is \s . Expand the whitespace selection from a single space to multiple using the \s+ RegEx.

How do you remove leading and trailing?

The Trim function The most obvious (and generally efficient) method for removing both leading and trailing space is to use the TRIM() function.


1 Answers

You can use str.trim() for this case. It removes the leading and trailing whitespace from a string. The regular expression str.replace(/^\s+|\s+$/g,'') will alternatively do the same thing.

like image 98
hexacyanide Avatar answered Nov 14 '22 17:11

hexacyanide