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.
Simple and well explained.