How to trim all non-alphanumeric characters from start and end of a string in Javascript?

javascript, regex

Solution

Modify your current RegExp to specify the start or end of string with `^` or `$` and make it greedy. You can then link the two together with an OR `|`.

val.replace(/^[^a-zA-Z0-9]*|[^a-zA-Z0-9]*$/g, '');

This can be simplified to `a-z` with `i` flag for all letters and `\d` for numbers

val.replace(/^[^a-z\d]*|[^a-z\d]*$/gi, '');

Problem

I have some strings that I want to clean up by removing all non-alphanumeric characters from the beginning and end. It should work on these strings: ``` )&*@^#*^#&^%$text-is.clean,--^2*%#**)(#&^ --->> text-is.clean,--^2 -+~!@#$%,.-"^&example-text@is.clean,--^#*%#**)(#&^ --->> example-text@is.clean ``` I have this regex, which removes them from the whole string: ``` val.replace(/[^a-zA-Z0-9]/g,'') ``` How would I change it to only remove from the beginning and end of string?

Original source