How can I ltrim and rtrim select characters in Javascript?

时间:2017-10-24 14:42:48

标签: javascript regex

So I am trying to figure out how I can remove a select set of characters on the end of a string. I've tried some general 'solutions' like str.replace or creating a rtrim, but I kept seeing some situation in which it wouldn't work.

Possible inputs might be:

\r\n some random text \r\n
\r\n some random text
some random text \r\n
some random text

Only the first and the third line should be affected by this function. Basicly I'm looking for a rtrim function that takes as a parameter, the value/character set that should be trimmed.

I think it might be something way too obvious that I don't see, but at this point I feel like I could use some help.

1 个答案:

答案 0 :(得分:2)

您可以使用以下代码为您执行此操作:

var a = "\r\n some random text \r\n";
a = a.replace(new RegExp('\r\n$'), '');

此处,$匹配输入的结尾。

您可以参考正则表达式指南here以了解有关JS中正则表达式的更多信息。

修改

如果你真的需要一个功能:

var rTrimRegex = new RegExp('\r\n$');
var rTrim = function(input){
    return input.replace(rTrimRegex, '');
}

然后在代码中使用它可能就像:

var str = 'my name is foo\r\n\r\n';
str = rTrim(str);