0

Im trying to find a solution to remove all instances of a given character from the beginning and end of a string.

Example:

// 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 

This function would effectively be to trim what replaceAll is to replace.

My replaceAll solutions is as follows:

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

This would of course replace all instances of a character in the string, as opposed to just form both ends.

What Regex would be best in this instance?

yevg
  • 1,846
  • 9
  • 34
  • 70

2 Answers2

3

One option uses replace:

var string = '""and then she said "hello, world" and walked away""';
string = string.replace(/"*(.*[^"])"*$/, "$1");
console.log(string);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

I this case you can use:

string  = string.replace(/^"|"$/g, '');

If you want to remove (trim) all such characters (linke ") use:

string = string.replace(/^["]+|["]+$/g, '');

In this way you can also define rtrim (right trim) or ltrim:

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

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

I hope these help you.

adel
  • 832
  • 5
  • 10