本文介绍了regexp只允许在单词之间留一个空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个正则表达式来从单词的开头删除空格,而不是在单词后面的单个空格中删除空格。

I'm trying to write a regular expression to remove white spaces from just the beginning of the word, not after, and only a single space after the word.

使用RegExp:

var re = new RegExp(/^([a-zA-Z0-9]+\s?)*$/);

测试Exapmle:

1) test[space]ing - Should be allowed 
2) testing - Should be allowed 
3) [space]testing - Should not be allowed 
4) testing[space] - Should be allowed but have to trim it 
5) testing[space][space] - should be allowed but have to trim it 

只允许一个空格。可能吗?

Only one space should be allowed. Is it possible?

推荐答案

function validate(s) {
    if (/^(\w+\s?)*\s*$/.test(s)) {
        return s.replace(/\s+$/, '');
    }
    return 'NOT ALLOWED';
}
validate('test ing')    // => 'test ing'
validate('testing')     // => 'testing'
validate(' testing')    // => 'NOT ALLOWED'
validate('testing ')    // => 'testing'
validate('testing  ')   // => 'testing'
validate('test ing  ')  // => 'test ing'

BTW,新的RegExp(..)是多余的。

这篇关于regexp只允许在单词之间留一个空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 17:43