TheGreenGentleman
TheGreenGentleman

Reputation: 95

JavaScript Count String Without Spaces

GEN000 AMA000 GaT000   

I only need to count the number of text without the spaces

Upvotes: 1

Views: 6525

Answers (3)

Lee Taylor
Lee Taylor

Reputation: 7984

var text = "GEN000 AMA000 GaT000";
var length = text.split(" ").join("").length;

console.log(length);

Upvotes: 4

Anand Jha
Anand Jha

Reputation: 10714

Try this simple solution,

alert(str.replace(/\s/g, "").length);

Example

Upvotes: 2

VisioN
VisioN

Reputation: 145398

Just as an alternative approach:

'GEN000 AMA000 GaT000'.match(/\S/g).length;  // 18

However, the fastest solution should always be a single for loop:

var str = 'GEN000 AMA000 GaT000',
    count = 0;

for (var i = 0, len = str.length; i < len; i++) {
    if (str[i] !== ' ')
        count++;
}

Upvotes: 5

Related Questions