什么是 JavaScript 等效于此 C#
方法:
var x = "|f|oo||";
var y = x.Trim('|'); // "f|oo"
C# 仅在字符串的开头 和结尾 trim 所选字符!
最佳答案
一行就够了:
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 = "\\^";
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));
}
参数c
应该是一个字符(长度为1的字符串)。
如评论中所述,支持多个字符可能很有用,因为例如 trim 多个类似空白的字符是很常见的。为此,MightyPork建议将 if
替换为以下代码行:
c = c.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
这部分[-/\\^$*+?.()|[\]{}]
是正则表达式语法中的一组特殊字符,$&
是一个占位符,代表匹配字符,意味着 replace
函数转义特殊字符。在您的浏览器控制台中尝试:
> "{[hello]}".replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
"\{\[hello\]\}"
关于javascript - 从字符串中 trim 特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26156292/