How to count the number of characters without spaces?

I'm new to this, so please understand me; /

I am creating an application in appery.io and it should count the number of letters of text inserted by the user of the application (no spaces).

I have an input field entered (input), a button to click and display the result in a label (result)

button code:

var myString = getElementById("input");

var length = myString.length;

Apperyio('result').text(length);

      

Could you tell me what is wrong?

+4


source to share


3 answers


To ignore literal whitespace, you can use a regular expression with whitespace:

// get the string
let myString = getElementById("input").value;

// use / /g to remove all spaces from the string
let remText = myString.replace(/ /g, "");

// get the length of the string after removal
let length = remText.length;

      



To ignore all spaces (newlines, spaces, tabs), use the \ s quantifier:

// get the string
let myString = getElementById("input").value;

// use the \s quantifier to remove all white space
let remText = myString.replace(/\s/g, "")

// get the length of the string after removal
let length = remText.length;

      

+11


source


Use this:



var myString = getElementById("input").value;
var withoutSpace = myString.replace(/ /g,"");
var length = withoutSpace.length;

      

+6


source


You can count the spaces and subtract it from the length of the string, like

var my_string = "John Doe iPhone6";
var spaceCount = (my_string.split(" ").length - 1);
console.log(spaceCount);
console.log('total count:- ', my_string.length - spaceCount)

      

-1


source







All Articles