What's the JavaScript equivalent to this C#
Method:
var x = "|f|oo||";
var y = x.Trim('|'); // "f|oo"
C# trims the selected character only at the beginning and end of the string!
javascriptstringtrim
What's the JavaScript equivalent to this C#
Method:
var x = "|f|oo||";
var y = x.Trim('|'); // "f|oo"
C# trims the selected character only at the beginning and end of the string!
Best Answer
One line is enough:
A general solution:
Parameter
c
is expected to be a character (a string of length 1).As mentionned in the comments, it might be useful to support multiple characters, as it's quite common to trim multiple whitespace-like characters for example. To do this, MightyPork suggests to replace the
if
s with the following line of code:This part
[-/\\^$*+?.()|[\]{}]
is a set of special characters in regular expression syntax, and$&
is a placeholder which stands for the matching character, meaning that thereplace
function escapes special characters. Try in your browser console: