Varathan Swaminath Varathan Swaminath - 4 months ago 10
Javascript Question

I need a regular expression to remove white space in the beginning and it should allow spaces in between two words

Here is my source code. I have written a directive in angularjs to eliminate spaces. It's perfectly working for spaces between words but is still allowing spaces at the beginning.

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;
});
}
};
}

Answer

If you want to remove whitespace just from the beginning

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