Javascript 从字符串的开头和结尾删除字符的所有实例

Javascript 从字符串的开头和结尾删除字符的所有实例,javascript,regex,replaceall,Javascript,Regex,Replaceall,我试图找到一个解决方案,从字符串的开头和结尾删除给定字符的所有实例 示例: // Trim all double quotes (") from beginnning and end of string let string = '""and then she said "hello, world" and walked away""'; string = string.trimAll('"',string); console.log(string); // and then she s

我试图找到一个解决方案,从字符串的开头和结尾删除给定字符的所有实例

示例:

// Trim all double quotes (") from beginnning and end of string

let string = '""and then she said "hello, world" and walked away""';

string = string.trimAll('"',string); 

console.log(string); // and then she said "hello, world" and walked away 
此功能实际上是为了
trim
replaceAll
是为了
replace

我的所有解决方案如下:

String.prototype.replaceAll = function(search, replacement) {
    return this.replace(new RegExp(search, 'g'), replacement);
};
这当然会替换字符串中字符的所有实例,而不仅仅是两端的形式


在这种情况下,哪个正则表达式最好?

一个选项使用
替换

var string='”,然后她说“你好,世界”,然后走开了;
字符串=字符串。替换(/“*(.[^”])“*$/,“$1”);

console.log(字符串);
一个选项使用
替换:

var string='”,然后她说“你好,世界”,然后走开了;
字符串=字符串。替换(/“*(.[^”])“*$/,“$1”);

console.log(字符串)I在这种情况下,您可以使用:

string  = string.replace(/^"|"$/g, '');
如果要删除(修剪)所有此类字符(链接),请使用:

通过这种方式,您还可以定义rtrim(右修剪)或ltrim:

// ltirm
string = string.replace(/^"/, '');

// rtirm
string = string.replace(/"$/, '');

我希望这些对您有所帮助。

我希望您可以使用此案例:

string  = string.replace(/^"|"$/g, '');
如果要删除(修剪)所有此类字符(链接),请使用:

通过这种方式,您还可以定义rtrim(右修剪)或ltrim:

// ltirm
string = string.replace(/^"/, '');

// rtirm
string = string.replace(/"$/, '');

我希望这些对您有所帮助。

请记住,变异内置对象是非常糟糕的做法-改为调用函数。请记住,变异内置对象是非常糟糕的做法-改为调用函数。您可能需要
string.replace(/^“*|“*$/g)”)
,但这是一个很好的答案。您可能需要
string.replace(/^“*|”*$/g,”)
,但这是一个很好的答案。