Reputation: 49
I've these strings:
"#ab#ab #ab # ab # a #a "
and
"ab ab ab ab a a "
so I want get this from the strings:
"ab ab ab ab a a"
(without leading and last space)
But
now I use two regexes:
replace(/#/gi, ' ')
and replace(/ (?!\w)/gi, '')
and my regexes are not perfect. I want use one nice regex.
Can you help me?
Upvotes: 3
Views: 165
Reputation: 87203
Use following regex(Thanks to @Avinash Raj)
[\s#]+
Also use trim
on the replaced string to remove leading and trailing spaces if any.
Demo:
var str = '#ab#ab #ab # ab # a #a';
str = str.replace(/[\s#]+/g, ' ').trim();
console.log(str);
document.write(str);
/\s*(?:#|\s)\s*/g
\s*
: Matches any number of spaces(?:...)
: Non-capturing group#|\s
: Matches #
literal or a space charactervar str = '#ab#ab #ab # ab # a #a';
str = str.replace(/\s*(?:#|\s)\s*/g, ' ').trim();
console.log(str);
document.write(str);
Upvotes: 3