Reputation: 31
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!
Upvotes: 1
Views: 149
Reputation: 10096
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(''));
Upvotes: 0
Reputation: 386578
You could replace whitespace or the last found n
.
var string = 'j o h n';
console.log(string.replace(/\s|n$/gi, ''));
Upvotes: 0
Reputation: 626806
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).Upvotes: 2