user1
user1

Reputation: 1065

Javascript: remove trailing spaces only

Can anyone help me on how to remove trailing spaces in JavaScript. I want to keep the leading spaces as is and only remove trailing spaces.
EG: ' test ' becomes ' test'. Seems like pretty simple but I can't figure it out.

PS: I am pretty sure I can't be the first one to ask this but I can't find an answer in SO. Also, I am looking for JavaScript solution. I am not using jQuery.

Upvotes: 18

Views: 18710

Answers (6)

MHart1000
MHart1000

Reputation: 21

Regex is worth knowing. But in case you don't, and don't want to use code you're not comfortable with, nor dive down that rabbit-hole for your current issue, here's a simple manual workaround:

/**
 * @example
 * trimEndSpaces('test   \n   '); // Returns: 'test   \n'
 * @param {string} str 
 * @returns {string}
 */
function trimEndSpaces(str) {
  let i = str.length - 1;
  // decrement index while character is a space
  while (str[i] === ' ') {
    i--;
  }
  // return string from 0 to non-space character
  return str.slice(0, i + 1);
}

Upvotes: 2

KyleMit
KyleMit

Reputation: 29829

Update 2019

String trim methods have been added to ECMAScript spec in 2019 with wide browser support

You can use like this:

" test ".trimEnd() // " test"

Further Reading

Upvotes: 3

Ashish Awasthi
Ashish Awasthi

Reputation: 94

There is a way by which you can create a regex inside the replace method like str.replace(/\s+$/g,'') will remove all trailing spaces.

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115212

Use String#replace with regex /\s+$/ and replacing text as empty string.

string.replace(/\s+$/, '')

console.log(
  '-----' + '    test    '.replace(/\s+$/, '') + '-----'
)

Upvotes: 30

Alexey Korsakov
Alexey Korsakov

Reputation: 312

"    test    ".replace(/\s+$/g, '');

Upvotes: 2

Vicky Kumar
Vicky Kumar

Reputation: 1408

use trimRight()

var x ="   test   "

x.trimRight()

Upvotes: 0

Related Questions