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,616
  • 4
  • 29
  • 64

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
  • 451,927
  • 24
  • 239
  • 318
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 Armand
  • 709
  • 4
  • 10