![](/img/trans.png)
[英]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.