1
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!

AAEM
  • 1,657
  • 1
  • 12
  • 25
  • Glad my answer worked for you. Please also consider upvoting all answers that proved helpful to you and that might be useful for future readers (see [How to upvote on Stack Overflow?](http://meta.stackexchange.com/questions/173399/how-to-upvote-on-stack-overflow)). With 15 rep points, you are entitled to upvoting on SO. – Wiktor Stribiżew May 18 '18 at 06:50

3 Answers3

2

You may use replace directly:

var name = 'j o h 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

Community
  • 1
  • 1
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
0

You could replace whitespace or the last found n.

var string = 'j o h n';

console.log(string.replace(/\s|n$/gi, ''));
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
0

You can either append another replace():

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

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

console.log("j o h n".split(/\s|n$/ig).join(''));
Luca Kiebel
  • 8,292
  • 5
  • 24
  • 37