[英]Create a function to remove all white spaces in string in JavaScript?
I'm trying to build a function to remove white spaces from both ends of a string (including \\n,\\t) without using built in functions (ie trim(), replace(), split(), join()) 我正在尝试构建一个函数来删除字符串两端的空格(包括\\ n,\\ t),而不使用内置函数(例如trim(),replace(),split(),join())
Similar to the following code but without the .replace: 与以下代码类似,但没有.replace:
function myTrim(x)
{
return x.replace(/^\s+|\s+$/gm,'');
}
function myFunction()
{
var str = myTrim(" Hello World! \t ");
}
Here it is using Regexp.exec
: 在这里,它使用
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 ")+']')
One thing to note is that you must re-call
re.exec
if the first result was non-null to clear the functions buffer.需要注意的一件事是,如果第一个结果非空,则必须重新调用
re.exec
才能清除函数缓冲区。
If you want to avoid built-in functions, you will have to iterate over your string. 如果要避免内置函数,则必须遍历字符串。
Here is a way to do it by iterating over the string 3 times: 这是通过对字符串进行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!')}]`);
If I understood correctly. 如果我理解正确。 Try this.
尝试这个。
x.replace(/[\n\t ]/g, "");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.