简体   繁体   中英

Regular expression javascript insert space

I have this regular expression in my javascript:

var name = '#tee name test ';
var title = name.replace(/[^a-z0-9]/gi,'');

This generate this title:

teenametest

But I'd want this:

tee name test

How can I allow space but remove other characters like '#'? Thanks

Change this line:

var title = name.replace(/[^a-z0-9]/gi,'');

To this:

var title = name.replace(/[^a-z0-9\s]/gi,'');

You need to tell the regex not to replace the spaces.

If you need to remove the last space, you can use the string.trim function.

If you still want to use regex to remove the last space as well, you can use:

var title = name.replace(/[^a-z0-9\s]|\s+$/gi,'');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM