小编典典

修剪字符串中的特定字符

javascript

与该方法等效的 JavaScript 是什么C#

var x = "|f|oo||"; 
var y = x.Trim('|'); //  "f|oo"

C#仅在字符串的 开头结尾 处修剪所选字符!


阅读 327

收藏
2020-05-01

共1个答案

小编典典

一行就足够了:

var x = '|f|oo||';

var y = x.replace(/^\|+|\|+$/g, '');

document.write(x + '<br />' + y);


^\|+   beginning of the string, pipe, one or more times
|      or
\|+$   pipe, one or more times, end of the string

在功能上:

function trim (s, c) {

  if (c === "]") c = "\\]";

  if (c === "\\") c = "\\\\";

  return s.replace(new RegExp(

    "^[" + c + "]+|[" + c + "]+$", "g"

  ), "");

}



chars = ".|]\\";

for (c of chars) {

  s = c + "foo" + c + c + "oo" + c + c + c;

  console.log(s, "->", trim(s, c));

}
2020-05-01