jQuery remove special characters from string and more

后端 未结 7 1716
北荒
北荒 2020-12-12 17:58

I have a string like this:

var str = \"I\'m a very^ we!rd* Str!ng.\";

What I would like to do is removing all special characters from the a

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 18:35

    Since I can't comment on Jasper's answer, I'd like to point out a small bug in his solution:

    str.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-');
    

    The problem is that first code removes all the hyphens and then tries to replace them :) You should reverse the replace calls and also add hyphen to second replace regex. Like this:

    str.replace(/[_\s]/g, '-').replace(/[^a-z0-9-\s]/gi, '');
    

提交回复
热议问题