简体   繁体   English

如何从 JavaScript 字符串末尾修剪特定字符?

[英]How to trim specific characters from end of JavaScript string?

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但没有成功

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

There are no trim, ltrim, or rtrim functions in Javascript. Javascript 中没有trim、ltrim 或rtrim 函数。 Many libraries provide them, but generally they will look something like:许多图书馆都提供它们,但通常它们看起来像:

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;
}

You can modify the String prototype if you like.如果您愿意,可以修改 String 原型。 Modifying the String prototype is generally frowned upon, but I personally prefer this method, as it makes the code cleaner IMHO.修改 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); 

IMO this is the best way to do a right/left trim and therefore, having a full functionality for trimming (since javascript supports string.trim natively) IMO 这是进行右/左修剪的最佳方式,因此具有完整的修剪功能(因为 javascript 原生支持string.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 '

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

"hi there~".replace(/~*$/, "")
str.trimEnd();
str.trimRight();

These are currently stage 4 proposals expected to be part of ES2019.这些目前是第 4 阶段的提案,预计将成为 ES2019 的一部分。 They work in NodeJS and several browsers.他们在 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

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'

My 2 cents:我的 2 美分:

function rtrim(str: string, ch: string): string
{
    var i:number = str.length - 1; 
    
    while (ch === str.charAt(i) && i >= 0) i--
    
    return str.substring(0, i + 1);
}

const tests = ["/toto/", "/toto///l/", "/toto////", "/////", "/"]

tests.forEach(test => {
    console.log(`${test} = ${rtrim(test, "/")}`)
})

Gives

"/toto/ = /toto"
"/toto///l/ = /toto///l"
"/toto//// = /toto"
"///// = "
"/ = "

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);
}

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

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