当字符串中存在多个空格时,字数不正确

时间:2015-12-08 14:36:34

标签: javascript function

此功能正常。 但是,如果我在str中添加更多的空格,那么它会给出错误的单词数。任何帮助,将不胜感激。

15:30:34 - INFO - Running: spec/controllers/advertisements_controller_spec.rb spec/routing/advertisements_routing_spec.rb
/Users/rudi/devel/w2b/app/controllers/advertisements_controller.rb:7:in `<class:AdvertisementsController>': undefined method `add_breadcrumb' for AdvertisementsController:Class (NoMethodError)
    from /Users/rudi/devel/w2b/app/controllers/advertisements_controller.rb:1:in `<top (required)>'
    from /Users/rudi/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.1/lib/active_support/dependencies.rb:274:in `require'
    from /Users/rudi/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.1/lib/active_support/dependencies.rb:274:in `block in require'
    from /Users/rudi/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.1/lib/active_support/dependencies.rb:240:in `load_dependency'
    from /Users/rudi/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.1/lib/active_support/dependencies.rb:274:in `require'
    from /Users/rudi/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.1/lib/active_support/dependencies.rb:360:in `require_or_load'
    from /Users/rudi/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.1/lib/active_support/dependencies.rb:494:in `load_missing_constant'
    from /Users/rudi/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.1/lib/active_support/dependencies.rb:184:in `const_missing'
    from /Users/rudi/devel/w2b/spec/controllers/advertisements_controller_spec.rb:3:in `<top (required)>'

2 个答案:

答案 0 :(得分:3)

尝试类似:

mystring.split(/\s+/);

这将拆分一个或多个空格字符,因此一行中的两个空格(或更多)将被视为一个拆分。

答案 1 :(得分:0)

let Allah = 'Allah    is our creator.'
Allah = Allah.trim();
count = 0;
for (let i = 0; i < Allah.length; i++) {
    let char = Allah[i];
    if (char == " " && Allah[i-1] != " ") {//add here
        count++;
    }
    
}
count++;
console.log(count);

//输出:4