简体   繁体   中英

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())

Similar to the following code but without the .replace:

function myTrim(x)     
{
  return x.replace(/^\s+|\s+$/gm,'');  
} 

function myFunction()
{
  var str = myTrim("    Hello World!   \t ");
}

Here it is using 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.

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:

  1. A first time to remove the leading spaces
  2. Then to remove the trailing spaces by iterating in reverse order
  3. And then a last time to reverse the inverted string generated by the last step

 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, "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM