简体   繁体   中英

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.
I've tried /\\sn/ig or /\\s[n]/ig but i can not seem to both remove spaces and the letter that I want. 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:

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

The regex is

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

It matches:

  • \\s+ - 1+ whitespace chars
  • (?: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 ).

Regex demo

You could replace whitespace or the last found n .

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

You can either append another replace() :

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

or just use the | operator to also remove the n at the end:

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

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