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
-+~!@#$%,.-"^&[email protected],--^#*%#**)(#&^ --->> [email protected]
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?
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, '');
Use anchors ^
and $
to match positions before first character and after last character in the string.
val.replace(/(^[^A-Za-z0-9]*)|([^A-Za-z0-9]*$)/g, '');
You can also shorten your code using \W
which means non-alphanumeric character, shortcut for [^a-zA-Z0-9_]
in case you want to keep underscore as well.
val.replace(/(^\W*)|(\W*$)/g, '');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With