Reputation: 61
I'm new to this, so please understand me;/
I'm creating an app in appery.io and it has to count the number of letters of text inserted by the app user(without spaces).
I have an input field created(input), a button to press and show the result in a label(result)
the code for the button:
var myString = getElementById("input");
var length = myString.length;
Apperyio('result').text(length);
Can you please tell me what is wrong?
Upvotes: 6
Views: 35320
Reputation: 752
Here's a way to count numbers and ignore everything else (not just spaces):
document.getElementById("button").addEventListener("click", function() {
var input = document.getElementById("input").value; // get textbox value
var count = input.match(/\d/g)?.length || 0; // get count, fallback to 0
window.console.log(count); // print result
});
<input id="input" />
<button type="button" id="button">Get Count</button>
Upvotes: 0
Reputation: 7
count = 0;
const textLenght = 'ABC ABC';
for (var i = 0, len = textLenght.length; i < len; i++) {
if (textLenght[i] !== ' ')
count++;
}
Upvotes: 1
Reputation: 3936
To ignore a literal space, you can use regex with a space:
// 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 white space(new lines, 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;
Upvotes: 18
Reputation: 434
You can count white spaces and subtract it from lenght of string for example
var my_string = "John Doe's iPhone6";
var spaceCount = (my_string.split(" ").length - 1);
console.log(spaceCount);
console.log('total count:- ', my_string.length - spaceCount)
Upvotes: 0
Reputation: 2023
Use this:
var myString = getElementById("input").value;
var withoutSpace = myString.replace(/ /g,"");
var length = withoutSpace.length;
Upvotes: 9