Ad

How To Restrict Space At The First Position In Javascript/Angular

- 1 answer

I have the below regEx to allow spaces in the middle of the word.

oninput="this.value = this.value.replace(/[^A-Za-z0-9-,.;'&/.() ]/g,'')"

How do i restrict space in the first position if the input box. Spaces in the middle are allowed.

Ad

Answer

Alternate between start-of-string anchor (with ^) followed by a space, and the rest of your negative character set:

oninput="this.value = this.value.replace(/[^A-Za-z0-9-,.;'&/.() ]|^ /g,'')"

<input oninput="this.value = this.value.replace(/[^A-Za-z0-9-,.;'&/.() ]|^ /g,'')" value=" foo bar">

Ad
source: stackoverflow.com
Ad