【问题标题】:Iterating over a string and removing spaces Javascript Jquery [duplicate]遍历字符串并删除空格Javascript Jquery [重复]
【发布时间】:2014-08-05 06:57:18
【问题描述】:

我正在尝试遍历字符串并删除所有空格。 js 控制台告诉我关于第 1 行的信息:Uncaught SyntaxError: Unexpected end of input。

userinput 连接到 id 为“number”的输入标签

任何想法将不胜感激。

userinput = $('input#number').val();


function thing(x) {
    for (i = 0; i <= x.length(); i++) {
        if (x.charAt(i) === (" ")) {
            return x.indexOf(i).replace("")
        }
    }
    $(document).ready(function() {
        $('form#factorial').submit(function(event) {

            console.log(thing(userinput));
            event.preventDefault();

        });
    });

}

【问题讨论】:

  • 不会更简单 string.replace(/ /g,'') 吗?
  • 我同意@Dayan Moreno Leon,你为什么不能使用内置的字符串替换方法?

标签: javascript jquery html


【解决方案1】:

这段代码更短,删除空格更有效。

var str = 'this is my sentence';
str = str.split(' ').join(''); //str === 'thisismysentence';

如果你这样做,它应该是

for (i = 0; i <= x.length; i++) {

不是

for (i = 0; i <= x.length(); i++) {

您的函数中还缺少一个 }。

【讨论】:

    猜你喜欢
    • 2021-06-19
    • 2010-11-12
    • 2014-08-26
    • 2021-12-10
    • 1970-01-01
    • 2018-08-22
    • 2019-07-11
    • 2017-08-29
    相关资源
    最近更新 更多