最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Trim blank spaces from the right in jQuery - Stack Overflow

programmeradmin5浏览0评论

I see the trim method in jQuery, but I can't find, in its documentation, how to trim blank spaces from only the right of the string.

As an example, if I have:

"foobar "        "foo "         " foo bar  "

Trimming the spaces from the right of the string results in:

"foobar"         "foo"          " foo bar" 

Is there any method in jQuery to trim the spaces from the right? I mean, something like ltrim and rtrim?

I see the trim method in jQuery, but I can't find, in its documentation, how to trim blank spaces from only the right of the string.

As an example, if I have:

"foobar "        "foo "         " foo bar  "

Trimming the spaces from the right of the string results in:

"foobar"         "foo"          " foo bar" 

Is there any method in jQuery to trim the spaces from the right? I mean, something like ltrim and rtrim?

Share Improve this question edited Oct 12, 2016 at 4:02 Pang 10.1k146 gold badges86 silver badges124 bronze badges asked Oct 16, 2013 at 3:34 PaladiniPaladini 4,57215 gold badges57 silver badges97 bronze badges 3
  • There is no rtrim or ltrim in jQuery core. There are plugins or you can just use a basic reg exp to do it. – epascarello Commented Oct 16, 2013 at 3:37
  • Thanks @epascarello . I think that's a little thing that can be improved in the newest versions of jQuery - will be very useful. – Paladini Commented Oct 16, 2013 at 3:41
  • 1 They are not going to add that to jQuery core. Proof: bugs.jquery./ticket/9542 – epascarello Commented Oct 16, 2013 at 5:12
Add a ment  | 

4 Answers 4

Reset to default 10

You can use a simple regex replace

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

Demo: Fiddle

function rtrim(str){
    return str.replace(/\s+$/, '');
}

jQuery doesn't have the methods ltrim or rtrim.

You can do it easily:

function rtrim(str){
    return str.replace(/\s+$/, "");
}
function ltrim(str){
    return str.replace(/^\s+/, "");
}

I don't suggest you add a method on the String prototype.

you could do:

String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}

var str = "test ";
console.log(str.rtrim());

You can do something like this too:

 "foobar ".substring(0,"foobar ".length-1)

I'm not really into jQuery so you may need to use

  var yourstring ="something ";
发布评论

评论列表(0)

  1. 暂无评论