Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 481
Alexandru R Avatar asked Aug 15 '13 10:08

Alexandru R


2 Answers

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, '');
like image 177
Paul S. Avatar answered Sep 29 '22 10:09

Paul S.


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, ''); 
like image 29
Michal Klouda Avatar answered Sep 29 '22 10:09

Michal Klouda