修剪字符串中的特定字符
2022-08-30 01:35:17
与此方法等效的 JavaScript 是什么:C#
var x = "|f|oo||";
var y = x.Trim('|'); // "f|oo"
C# 仅在字符串的开头和结尾处修剪所选字符!
与此方法等效的 JavaScript 是什么:C#
var x = "|f|oo||";
var y = x.Trim('|'); // "f|oo"
C# 仅在字符串的开头和结尾处修剪所选字符!
一行就足够了:
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));
}
参数应为字符(长度为 1 的字符串)。c
正如注释中提到的,支持多个字符可能很有用,因为例如修剪多个类似空格的字符是很常见的。为此,MightyPork 建议将 s 替换为以下代码行:if
c = c.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
此部分是正则表达式语法中的一组特殊字符,是代表匹配字符的占位符,这意味着该函数转义特殊字符。在浏览器控制台中试用:[-/\\^$*+?.()|[\]{}]
$&
replace
> "{[hello]}".replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
"\{\[hello\]\}"
更新:我对不同解决方案的性能感到好奇,所以我在这里更新了一个基本的基准:https://www.measurethat.net/Benchmarks/Show/12738/0/trimming-leadingtrailing-characters
在Chrome下运行的一些有趣且意想不到的结果。https://www.measurethat.net/Benchmarks/ShowResult/182877
+-----------------------------------+-----------------------+
| Test name | Executions per second |
+-----------------------------------+-----------------------+
| Index Version (Jason Larke) | 949979.7 Ops/sec |
| Substring Version (Pho3niX83) | 197548.9 Ops/sec |
| Regex Version (leaf) | 107357.2 Ops/sec |
| Boolean Filter Version (mbaer3000)| 94162.3 Ops/sec |
| Spread Version (Robin F.) | 4242.8 Ops/sec |
+-----------------------------------+-----------------------+
请注意;测试仅对单个测试字符串执行(前导和尾随字符都需要修剪)。此外,此基准测试仅提供原始速度的指示;其他因素(如内存使用情况)也很重要。
如果您正在处理较长的字符串,我相信通过将分配的字符串数量减少到零或一,这应该优于大多数其他选项:
function trim(str, ch) {
var start = 0,
end = str.length;
while(start < end && str[start] === ch)
++start;
while(end > start && str[end - 1] === ch)
--end;
return (start > 0 || end < str.length) ? str.substring(start, end) : str;
}
// Usage:
trim('|hello|world|', '|'); // => 'hello|world'
或者,如果要从一组多个字符中修剪:
function trimAny(str, chars) {
var start = 0,
end = str.length;
while(start < end && chars.indexOf(str[start]) >= 0)
++start;
while(end > start && chars.indexOf(str[end - 1]) >= 0)
--end;
return (start > 0 || end < str.length) ? str.substring(start, end) : str;
}
// Usage:
trimAny('|hello|world ', [ '|', ' ' ]); // => 'hello|world'
// because '.indexOf' is used, you could also pass a string for the 2nd parameter:
trimAny('|hello| world ', '| '); // => 'hello|world'
编辑:为了好玩,修剪单词(而不是单个字符)
// Helper function to detect if a string contains another string
// at a specific position.
// Equivalent to using `str.indexOf(substr, pos) === pos` but *should* be more efficient on longer strings as it can exit early (needs benchmarks to back this up).
function hasSubstringAt(str, substr, pos) {
var idx = 0, len = substr.length;
for (var max = str.length; idx < len; ++idx) {
if ((pos + idx) >= max || str[pos + idx] != substr[idx])
break;
}
return idx === len;
}
function trimWord(str, word) {
var start = 0,
end = str.length,
len = word.length;
while (start < end && hasSubstringAt(str, word, start))
start += word.length;
while (end > start && hasSubstringAt(str, word, end - len))
end -= word.length
return (start > 0 || end < str.length) ? str.substring(start, end) : str;
}
// Usage:
trimWord('blahrealmessageblah', 'blah');