Stan Knock
Stan Knock

Reputation: 49

Once universal regex for tags

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

Answers (1)

Tushar
Tushar

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);

Regex Demo and Explanation

/\s*(?:#|\s)\s*/g
  1. \s*: Matches any number of spaces
  2. (?:...): Non-capturing group
  3. #|\s: Matches # literal or a space character

var str = '#ab#ab #ab # ab #  a  #a';
str = str.replace(/\s*(?:#|\s)\s*/g, ' ').trim();

console.log(str);
document.write(str);

Upvotes: 3

Related Questions