Roni Tovi
Roni Tovi

Reputation: 886

regex replace all matches based on pattern

var testString = 'Please use "command1" to accept and "command2" to ignore';

All I'm trying to achive is replacing the string between the quotes but when replacing, I need to know what was inside the quotes.

After replacing it should be like:

var result = 'Please use <a href="someurl?cmd=command1">command1</a> to accept and <a href="someurl?cmd=command2">command2</a> to ignore';

I tried somethiing like this with no success:

            var rePattern = /\"(.*?)\"/gi;
            Text.replace(rePattern, function (match, txt, urlId) {
                return "rendered link for " + match;
            });

Upvotes: 0

Views: 1646

Answers (3)

theftprevention
theftprevention

Reputation: 5213

You should check out MDN's documentation on String.prototype.replace(), specifically the section about Specifying a function as a parameter.

var testString = 'Please use "command1" to accept and "command2" to ignore';
var reg = /"([^"]+)"/g;
var testResult = testString.replace(reg, function (match, p1) {
    return '<a href="someurl?cmd=' + p1 + '">' + p1 + '</a>';
});

The first parameter to replace is the regular expression, and the second parameter is an anonymous function. That function is sent four arguments (see MDN's documentation), but we're only using the first two: match is the entire matched string -- either "command1" or "command2" -- and p1 is the content of the first capture group in the regular expression, either command1 or command2 (without quotes). The string returned by this anonymous function is what those matches are replaced with.

Upvotes: 1

ʰᵈˑ
ʰᵈˑ

Reputation: 11375

You can use a capture group and then reference it in a replace.

Find

/\"([^\"]+)\"/gm

Then replace

<a href="someurl?cmd=$1">$1</a>

https://regex101.com/r/kG3iL4/1

var re = /\"([^\"]+)\"/gm; 
var str = 'Please use "command1" to accept and "command2" to ignore';
var subst = '<a href="someurl?cmd=$1">$1</a>'; 

var result = str.replace(re, subst);

Upvotes: 0

Oriol
Oriol

Reputation: 288260

You can use the regex /"(.+?)"/g to match all quoted text, with a capture group for the command without the quotes. Then you can use "$1" in the replacement string.

'Please use "command1" to accept and "command2" to ignore'
.replace(/"(.+?)"/g, '<a href="someurl?cmd=$1">$1</a>');

Upvotes: 1

Related Questions