【问题标题】:I need a regular expression to remove white space in the beginning and it should allow spaces in between two words [duplicate]我需要一个正则表达式来删除开头的空格,它应该允许两个单词之间有空格[重复]
【发布时间】:2016-07-08 14:58:13
【问题描述】:

这是我的源代码。我在 angularjs 中编写了一个指令来消除空格。它非常适合单词之间的空格,但仍然允许开头有空格。

function customValidation() {

   return {
     require: 'ngModel',
     link: function(scope, element, attrs, modelCtrl) {

       modelCtrl.$parsers.push(function (inputValue) {

         var transformedInput = inputValue.toLowerCase().replace(/ /g,''); 

         if (transformedInput!== inputValue) {
           modelCtrl.$setViewValue(transformedInput);
           modelCtrl.$render();
         }         

         return transformedInput;         
       });
     }
   };
}

【问题讨论】:

  • ngTrim 设置为false。见stackoverflow.com/a/32135166/3832970
  • 我已经将 ngTrim 的值设置为 false..
  • 我怀疑你只是想要.replace(/\s+/g,'');
  • @WiktorStribiżew,马丁已经回答了!
  • @TilakMadichetti:怎么样?找出 1 个重要的区别。

标签: javascript angularjs regex


【解决方案1】:

如果您只想从开头删除空格

inputValue.toLowerCase().replace(/^\s+/, '').replace(/\s+/g, ' '); 

【讨论】:

  • 嗨马丁,谢谢你,你的例子对我有用,但我的情况是它不应该在开头允许空格,它应该只允许一个单词后的一个空格。但是您给出的正则表达式是在单词后接受更多的空格。如果您有任何想法可以消除单词后的更多空格,请分享谢谢...
  • 在当前方法的上下文中,/g 在这里完全没有意义。一个字符串中可以有多少个字符串的开头?是的,1。
  • @VarathanSwaminath - 当然,已更新以删除单词之间的多个空格。 Wiktor - 好点子!
  • @martin 非常感谢它的工作...... :)
猜你喜欢
  • 1970-01-01
  • 2020-05-09
  • 2013-03-06
  • 1970-01-01
  • 1970-01-01
  • 2016-06-09
  • 2021-01-06
相关资源
最近更新 更多