Reputation: 13
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.
Upvotes: 0
Views: 4376
Reputation: 33439
This one works a little bit like CertainPerformance's answer, but save's the caret position and doesn't jump to the end of the input
Added some visual feedback
;(() => {
const inp = document.querySelector('#inp');
const nospaces = function(elem) {
// find spaces at start of input
const spacesReg = /^\s+/;
let match
if (match = elem.value.match(spacesReg)) {
// save current caret position
const pos = elem.selectionStart;
const len = match[0].length;
elem.value = elem.value.replace(spacesReg, '');
// reset caret position
elem.selectionStart = elem.selectionEnd = Math.min(0, pos - len)
return true
}
return false
}
const onlyAllowedCharacters = function(elem) {
// search for not allowed characters
const allowed = "A-Za-z0-9-,.;'&/.() ";
const notAllowedReg = new RegExp(`(.*?)[^${allowed}]`);
// prevent infinite loop
var max = 255;
let match;
let blink = false
// replace one not allowed character per loop run
while ((max > 0) && (match = elem.value.match(notAllowedReg))) {
blink = true
const pos = elem.selectionStart;
const len = match[1].length
elem.value = elem.value.replace(notAllowedReg, '$1');
elem.selectionStart = elem.selectionEnd = pos - 1
max--
}
return blink;
}
const blink = function(elem, duration = 200) {
const to = setTimeout(() => {
elem.classList.remove('blink')
}, duration)
elem.classList.add('blink')
}
// use function literal to get correct `this` value
inp.addEventListener('input', function(e) {
const nosp = nospaces(this);
const only = onlyAllowedCharacters(this);
if (nosp || only) {
blink(this)
}
})
})();
.blink {
background: red;
}
No spaces at start of input<br>
Only allowed characters a–zA–Z0–9-,.;'&\.()<br>
<input type="text" id="inp">
Upvotes: 1
Reputation: 370879
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">
Upvotes: 4
Reputation: 44115
Just trim
the string before you replace
it:
oninput="this.value = this.value.trim().replace(/[^A-Za-z0-9-,.;'&/.() ]/g,'')"
Upvotes: 1
Reputation: 4884
You can use built in String method trim()
. trim()
method in javascript removes spaces from the starting and ending of the string.
this.value = this.value.trim()
// if you want to apply regex also, you can try the below code
this.value = this.value.replace(/[^A-Za-z0-9-,.;'&/.() ]|^ /g,'').trim()
const a = ' hello '
console.log(a.trim())
// hello
Upvotes: 2