XTRUST.ORG
XTRUST.ORG

Reputation: 3392

javascript | String replace using regex

I have a class string: width-100 required validate-email validate-unique-email input-success And would like to find (special formatted) substring. Result should be: validate-email validate-unique-email

My code:

var ok = "width-100 required validate-email validate-unique-email input-success".replace(/validate-([A-Z]+)/gi, function(match, $1, $2) {
   return $1;
});

console.log(ok);

But this doesn't work. Where is a mistake? Thanks!

Upvotes: 0

Views: 47

Answers (4)

Avinash Raj
Avinash Raj

Reputation: 174696

You could use a lookahead here,

/\bvalidate-([A-Z-]+)(?= |$)/gi

Example:

> var str = "width-100 required validate-email validate-unique-email input-success";
undefined
> console.log(str.match(/\bvalidate-([A-Z-]+)(?= |$)/gi).join(' '));
validate-email validate-unique-email

Upvotes: 1

axelduch
axelduch

Reputation: 10849

This worked for me, you don't actually need to replace, this is why I used String.prototype.match instead

var str = "width-100 required validate-email validate-unique-email input-success";

console.log(str.match(/\bvalidate-([a-z]+)/gi).join(' '));

Upvotes: 1

Matyas
Matyas

Reputation: 13702

You could do something like below:

Code

var ok=[];
var str = 'width-100 required validate-email validate-unique-email input-success';

str.replace(/(\bvalidate-\w+\b)/gi, function(match) {
   ok.push(match);
});

console.log(ok);

Output

['validate-email', 'validate-unique']

Note

In this case replace is used only to iterate through the matches, and not really for replacing actual bits of str.

Upvotes: 0

vks
vks

Reputation: 67968

\bvalidate-[a-zA-Z0-9-]+\b

Try this.This will catch word matches.

http://regex101.com/r/kO7lO2/2

Upvotes: 0

Related Questions