4

How to Trim a Specific Character from the Start and End of a String using JavaSc...

 3 years ago
source link: https://www.codexworld.com/how-to/trim-specific-character-from-start-and-end-of-string-using-javascript/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Home  »  How To Guides  »  JavaScript   »   How to Trim a Specific Character from the Start and End of a String using JavaScript?

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.

Leave a reply

Cancel

Comment*

Your Name*

Your Email*

Your Website


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK