Swapnil Sharma
Swapnil Sharma

Reputation: 51

Remove spaces using javascript

How to remove all spaces from string using javascript. I have a code like this--

var Title = "";
var Str="g g";
Title = Str.replace(/^\s+|\s+$/g, '');
this gives me result Title=g g
how to get result Title=gg

Upvotes: 0

Views: 835

Answers (4)

Răzvan Flavius Panda
Răzvan Flavius Panda

Reputation: 22106

You can just use:

var Str="g g";
Str.replace(" ", "");

Upvotes: 0

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

Change code to:

var title = Str.replace(/\s+/g, '');

Your original regular expression would trim spaces only from the beginning or the end of the string.

Upvotes: 0

yogi
yogi

Reputation: 19591

Try this

Title = Str.replace(/ /g, '');

Upvotes: 0

WTK
WTK

Reputation: 16951

Use following regexp:

Str.replace(/\s+/g, '');

The one you have right now just strippes spaces from start or end of your string.

Upvotes: 2

Related Questions