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

时间:2018-05-13 02:28:28

标签: 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 said "hello, world" and walked away 

此功能实际上是trim replaceAllreplace的内容。

我的replaceAll解决方案如下:

String.prototype.replaceAll = function(search, replacement) {
    return this.replace(new RegExp(search, 'g'), replacement);
};

这当然会替换字符串中字符的所有实例,而不是仅仅形成两端。

在这种情况下,什么是正则表达式最好?

1 个答案:

答案 0 :(得分:3)

一个选项使用<div class ="wrapperDiv"> <section class="section sub-masthead--TC2"></section> <section class="section qualifiers--Q1"> <img src="https://placeimg.com/640/480/any" /> </section> </div>

&#13;
&#13;
replace
&#13;
&#13;
&#13;