简体   繁体   English

javascript正则表达式删除空格和字母

[英]javascript regex remove white space and a letter

var name = 'j o h n';

arr = name.split(/\s/ig).join('');

I'm wanting to remove the spaces and the letter 'n' from the end. 我想从末尾删除空格和字母“ n”。
I've tried /\\sn/ig or /\\s[n]/ig but i can not seem to both remove spaces and the letter that I want. 我已经尝试过/\\sn/ig/\\s[n]/ig但是我似乎无法同时删除空格和想要的字母。 I've search the web to see how to do this but haven't really found something to clearly explain how to put in multiple put in multiple expressions into the pattern. 我已经在网络上搜索了如何执行此操作,但是并没有真正找到可以清楚地说明如何将多个表达式放入模式中的东西。

Thanks! 谢谢!

You may use replace directly: 您可以直接使用replace

 var name = 'joh n'; console.log(name.replace(/\\s+(?:n$)?/gi, '')) 

The regex is 正则表达式是

/\s+(?:n$)?/gi

It matches: 它匹配:

  • \\s+ - 1+ whitespace chars \\s+ -1+空格字符
  • (?:n$)? - and optional n at the end of the string (the (?:...)? is an optional (due to the ? quantifier that match 1 or 0 repetitions of the quantified subpattern) non-capturing group ). -和在字符串末尾的可选n(?:...)?是可选的(由于与量化子模式的1或0个重复匹配的?量词) 非捕获组 )。

Regex demo 正则表达式演示

You could replace whitespace or the last found n . 您可以替换空格或最后找到的n

 var string = 'joh n'; console.log(string.replace(/\\s|n$/gi, '')); 

You can either append another replace() : 您可以附加另一个replace()

 console.log("john".split(/\\s/ig).join('').replace("n", "")); 

or just use the | 或只使用| operator to also remove the n at the end: 运算符还可以在最后删除n

 console.log("john".split(/\\s|n$/ig).join('')); 

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

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