简体   繁体   English

Javascript:仅删除尾随空格

[英]Javascript: remove trailing spaces only

Can anyone help me on how to remove trailing spaces in JavaScript.任何人都可以帮助我如何删除 JavaScript 中的尾随空格。 I want to keep the leading spaces as is and only remove trailing spaces.我想保持前导空格不变,只删除尾随空格。
EG: ' test ' becomes ' test' . EG: ' test '变成' 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. PS:我很确定我不能成为第一个提出这个问题的人,但我在 SO 中找不到答案。 Also, I am looking for JavaScript solution.另外,我正在寻找 JavaScript 解决方案。 I am not using jQuery.我没有使用 jQuery。

Use String#replace with regex /\s+$/ and replacing text as empty string.使用String#replace和正则表达式/\s+$/并将文本替换为空字符串。

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

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

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

use trimRight()使用 trimRight()

var x ="   test   "

x.trimRight()

有一种方法可以在替换方法中创建正则表达式,例如 str.replace(/\s+$/g,'') 将删除所有尾随空格。

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:但是,如果您不这样做,也不想使用您不喜欢的代码,也不想为您当前的问题潜入那个兔子洞,这里有一个简单的手动解决方法:

let endTrim = ((str) => {
  let i = str.length - 1
  while(str[i] === ' ') {
    str = str.slice(0,i)
    i--
  }
  return str
})

Update 2019 2019 年更新

String trim methods have been added to ECMAScript spec in 2019 with wide browser support字符串修剪方法已于2019 年添加到ECMAScript 规范中,并提供广泛的浏览器支持

You can use like this:你可以这样使用:

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

Further Reading延伸阅读

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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