简体   繁体   English

正则表达式javascript插入空格

[英]Regular expression javascript insert space

I have this regular expression in my javascript: 我在我的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. 如果需要删除最后一个空格,可以使用string.trim函数。

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,'');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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