javascript 如何计算没有空格的字符数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26389745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to count the number of characters without spaces?
提问by user3096253
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).
我正在 appery.io 中创建一个应用程序,它必须计算应用程序用户插入的文本字母的数量(没有空格)。
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?
你能告诉我有什么问题吗?
回答by SReject
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:
要忽略所有空格(新行、空格、制表符),请使用 \s 量词:
// 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;
回答by Harutyun Abgaryan
Use this:
用这个:
var myString = getElementById("input").value;
var withoutSpace = myString.replace(/ /g,"");
var length = withoutSpace.length;
回答by Hemant Nagarkoti
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)