Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
110
rated 0 times [  114] [ 4]  / answers: 1 / hits: 69866  / 11 Years ago, wed, february 12, 2014, 12:00:00

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.



Used RegExp:



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


Test 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?


More From » regex

 Answers
46
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, new RegExp(..) is redundant if you use regular expression literal.


[#72571] Tuesday, February 11, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
efrainjamiry

Total Points: 234
Total Questions: 110
Total Answers: 112

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
efrainjamiry questions
;