How to Trim a Specific Character from the Start and End of a String using JavaScript?

Regular Expression (RegEx) is the easiest way to trim a specific character from a string in JavaScript. Use the JavaScript replace() method with RegEx to remove a specific character from the string.

The example code snippet helps to remove comma (,) characters from the start and end of the string using JavaScript.

var myString = ',codex,world,';
myString = myString.replace(/^,+|,+$/g, '');

An explanation of the regular expressions used in the above code snippet:

  • / – Start RegEx (/).
  • ^,+ – Match the start of the line (^) followed by a comma (,) 1 or more times (+).
  • | – or
  • ,+$ – Match a comma (,) 1 or more times (+) followed by the end of the line ($).
  • / – End RegEx (/)
  • g – “global” match and replace all.

1 Comment

  1. Asad Said...

Leave a reply

keyboard_double_arrow_up