问题描述
我在下面的regEx中允许单词中间留空格。
oninput="this.value = this.value.replace(/[^A-Za-z0-9-,.;'&/.() ]/g,'')"
输入框如何在第一位置限制空间。 中间有空格。
1楼
Bear Nithi
2
2019-02-21 07:51:20
您可以使用内置的String方法trim()
。
javascript中的trim()
方法从字符串的开头和结尾删除空格。
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
2楼
CertainPerformance
1
已采纳
2019-02-21 07:51:58
在字符串起始锚(带有^
)和空格以及其他否定字符集之间切换:
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">
3楼
Jack Bashford
1
2019-02-21 07:54:43
只需trim
字符串,然后再replace
它:
oninput="this.value = this.value.trim().replace(/[^A-Za-z0-9-,.;'&/.() ]/g,'')"
4楼
yunzen
0
2019-02-21 08:36:58
该命令的工作方式类似于的 ,但是保存插入号的位置,并且不会跳到输入的末尾
编辑
添加了一些视觉反馈
;(() => { 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">