gpt4 book ai didi

javascript - 如何删除字符串周围的特定字符?

转载 作者:IT王子 更新时间:2023-10-29 00:09:03 26 4
gpt4 key购买 nike

我有这个字符串:

var str = "? this is a ? test ?";

现在我想得到这个:

var newstr = "this is a ? test";

如你所见,我只想删除 ? 周围的 (在开头和结尾) 那个字符串 (不在字符串的中间)。如何使用 JavaScript 做到这一点?

这是我尝试过的:

var str = "? this is a ? test ?";
var result = str.trim("?");
document.write(result);

所以,如您所见,它不起作用。实际上我是一名 PHP 开发人员并且 trim() works well in PHP .现在我想知道我是否可以使用 trim() 在 JS 中执行此操作。


需要注意的是I can do that using regex ,但老实说,我讨厌这种工作的正则表达式。无论如何,有更好的解决方案吗?


编辑:正如评论中提到的,我需要删除字符串周围的 ? 和空格。

最佳答案

搜索字符掩码并返回其余的。

本提案使用bitwise not ~ 运算符用于检查。

~ is a bitwise not operator. It is perfect for use with indexOf(), because indexOf returns if found the index 0 ... n and if not -1:

value  ~value   boolean
-1 => 0 => false
0 => -1 => true
1 => -2 => true
2 => -3 => true
and so on

function trim(s, mask) {
while (~mask.indexOf(s[0])) {
s = s.slice(1);
}
while (~mask.indexOf(s[s.length - 1])) {
s = s.slice(0, -1);
}
return s;
}

console.log(trim('??? this is a ? test ?', '? '));
console.log(trim('abc this is a ? test abc', 'cba '));

关于javascript - 如何删除字符串周围的特定字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36390853/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com