Javascript javascript需要做一个正确的修剪

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8141718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:51:05  来源:igfitidea点击:

javascript need to do a right trim

javascripttrim

提问by Nate Pet

In javascript, how to I do a right trim?

在 javascript 中,如何进行正确的修剪?

I have the following:

我有以下几点:

    var s1 = "this is a test~";

     var s = s1.rtrim('~') 

but was not successful

但没有成功

回答by Rob W

Use a RegExp. Don't forget to escape special characters.

使用正则表达式。不要忘记转义特殊字符。

s1 = s1.replace(/~+$/, ''); //$ marks the end of a string
                            // ~+$ means: all ~ characters at the end of a string

回答by Scott A

There are no trim, ltrim, or rtrim functions in Javascript. Many libraries provide them, but generally they will look something like:

Javascript 中没有trim、ltrim 或rtrim 函数。许多图书馆都提供它们,但通常它们看起来像:

str.replace(/~*$/, '');

For right trims, the following is generally faster than a regex because of how regex deals with end characters in most browsers:

对于正确的修剪,由于大多数浏览器中正则表达式处理结束字符的方式,以下通常比正则表达式更快:

function rtrim(str, ch)
{
    for (i = str.length - 1; i >= 0; i--)
    {
        if (ch != str.charAt(i))
        {
            str = str.substring(0, i + 1);
            break;
        }
    } 
    return str;
}

回答by JP Richardson

You can modify the String prototype if you like. Modifying the String prototype is generally frowned upon, but I personally prefer this method, as it makes the code cleaner IMHO.

如果您愿意,可以修改 String 原型。修改 String 原型通常是不受欢迎的,但我个人更喜欢这种方法,因为它使代码更简洁恕我直言。

String.prototype.rtrim = function(s) { 
    return this.replace(new RegExp(s + "*$"),''); 
};

Then call...

然后打电话...

var s1 = "this is a test~";
var s = s1.rtrim('~');
alert(s); 

回答by wutz

A solution using a regular expression:

使用正则表达式的解决方案:

"hi there~".replace(/~*$/, "")

回答by Javid

IMO this is the best way to do a right/left trim and therefore, having a full functionality for trimming (since javascript supports string.trimnatively)

IMO 这是进行右/左修剪的最佳方式,因此具有完整的修剪功能(因为 javascriptstring.trim本身支持)

String.prototype.rtrim = function (s) {
    if (s == undefined)
        s = '\s';
    return this.replace(new RegExp("[" + s + "]*$"), '');
};
String.prototype.ltrim = function (s) {
    if (s == undefined)
        s = '\s';
    return this.replace(new RegExp("^[" + s + "]*"), '');
};

Usage example:

用法示例:

var str1 = '   jav '
var r1 = mystring.trim();      // result = 'jav'
var r2 = mystring.rtrim();     // result = '   jav'
var r3 = mystring.rtrim(' v'); // result = '   ja'
var r4 = mystring.ltrim();     // result = 'jav '

回答by JJ McKool

str.trimEnd();
str.trimRight();

These are currently stage 4 proposals expected to be part of ES2019. They work in NodeJS and several browsers.

这些目前是第 4 阶段的提案,预计将成为 ES2019 的一部分。他们在 NodeJS 和几个浏览器中工作。

See below for more info:

请参阅下文了解更多信息:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimEnd

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimEnd

回答by 100PercentVirus

This removes a specified string or character from the right side of a string

这将从字符串的右侧删除指定的字符串或字符

function rightTrim(sourceString,searchString) 
{ 
    for(;;) 
    {
        var pos = sourceString.lastIndexOf(searchString); 
        if(pos === sourceString.length -1)
        {
            var result  = sourceString.slice(0,pos);
            sourceString = result; 
        }
        else 
        {
            break;
        }
    } 
    return sourceString;  
}

Please use like so:

请像这样使用:

rightTrim('sourcecodes.....','.'); //outputs 'sourcecodes'
rightTrim('aaabakadabraaa','a');   //outputs 'aaabakadabr'

回答by Joshua Davison

This is old, I know. But I don't see what's wrong with substr...?

这是旧的,我知道。但我不明白 substr 有什么问题...?

function rtrim(str, length) {
  return str.substr(0, str.length - length);
}