[英]Remove all non alphanumeric and any white spaces in string using javascript
[英]Create a function to remove all white spaces in string in JavaScript?
我正在尝试构建一个函数来删除字符串两端的空格(包括\\ n,\\ t),而不使用内置函数(例如trim(),replace(),split(),join())
与以下代码类似,但没有.replace:
function myTrim(x)
{
return x.replace(/^\s+|\s+$/gm,'');
}
function myFunction()
{
var str = myTrim(" Hello World! \t ");
}
在这里,它使用Regexp.exec
:
var re = /^\\s*(\\S[\\S\\s.]*\\S)\\s*$/gm; function trim(str) { var b = re.exec(str); return (b !== null) ? (re.exec(str),b[1]) : ''; } console.log('['+trim("Hello World!")+']') console.log('['+trim(" Hello World!")+']') console.log('['+trim("Hello World! \\t ")+']') console.log('['+trim(" Hello World! \\t ")+']')
需要注意的一件事是,如果第一个结果非空,则必须重新调用
re.exec
才能清除函数缓冲区。
如果要避免内置函数,则必须遍历字符串。
这是通过对字符串进行3次迭代来实现的:
function myTrim(str) { const isSpace = c => c === ' ' || c === '\\n' || c === '\\r' || c === '\\t'; const loop = (str, fn) => { for (const c of str) fn(c) }; const loopReverse = (str, fn) => { for (let i = str.length - 1; i >= 0; --i) fn(str[i]) }; let out = ''; let found = false; loop(str, c => { if (!isSpace(c) || found) { found = true; out += c; } }); found = false; let reversed = ''; loopReverse(out, c => { if (!isSpace(c) || found) { found = true; reversed += c; } }); out = ''; loopReverse(reversed, c => out += c); return out; } console.log(`[${myTrim(' \\n Hello World! \\t ')}]`); console.log(`[${myTrim('Hello World! \\n \\t ')}]`); console.log(`[${myTrim('Hello World!')}]`);
如果我理解正确。 尝试这个。
x.replace(/[\n\t ]/g, "");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.