【问题标题】:How to count the number of characters without spaces?如何计算没有空格的字符数?
【发布时间】:2014-10-15 18:38:10
【问题描述】:

我是新手,所以请理解我;/

我正在 appery.io 中创建一个应用程序,它必须计算应用程序用户插入的文本字母的数量(不包括空格)。

我创建了一个输入字段(输入),一个按钮可以按下并在标签中显示结果(结果)

按钮的代码:

var myString = getElementById("input");

var length = myString.length;

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

你能告诉我有什么问题吗?

【问题讨论】:

  • getElementById("input").value
  • 那么,您能澄清一下您要实现的目标是什么吗?您是否要计算字符串中非空格的字符数?

标签: javascript


【解决方案1】:

要忽略文字空格,您可以使用带空格的正则表达式:

// 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;

要忽略所有空白(新行、空格、制表符),请使用 \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;

【讨论】:

    【解决方案2】:

    使用这个:

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

    【讨论】:

    • 如果你需要去除空格,一个技巧也可以是var newstring = myString.replace(/ /g,""); var length = newString.length。只是一种确保没有空格的快速方法。
    【解决方案3】:

    例如,您可以计算空格并将其从字符串长度中减去

    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)
    

    【讨论】:

    • 删除所有空格更简单,代码行数更少
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多