user8587769
user8587769

Reputation:

how to match a string of words using regex javascript

Am trying to find a regex expression for this result:

string => should be matched (a single word or set of words at the beginning or the ending)
 string  => should be matched (a single word or set of words in the middle)
{{string}} -- should not be matched (a single word or set of words surrounded by two "{}" should not be matched)

am using this regex in this function :

text = text.replace(RegExp("([^{]{2})[^(\d:)]" + aTags[index].textContent + "\w* 
([^}]{2})", 'i'), "{{" + index + ":" + aTags[index].textContent + "}}");

the function should find the textContent of an 'a' tag in a 'text' string and replace it by adding a digit and ':' to the beginning of the textContent so that the result should be something like this :

some text => will became => {{1:some text}}

regex on regex101

Upvotes: 0

Views: 3987

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You cannot use PCRE verbs like (*SKIP)(*F) in a JavaScript regex, i.e. you cannot skip a matched portion of text with the regex means only. In JavaScript, you may match and capture a part of the string you want to later analyze in the replacement callback method (JS String#replace accepts a callback as the replacement argument).

So, in your case the solution will look like

text = text.replace(RegExp("{{.*?}}|(" + aTags[index].textContent + ")", "gi"),
    function ($0, $1) { 
        return $1 ? "{{" + index + ":" + $1 + "}}" : $0; 
    }
);

I understand the aTags[index].textContent value is alphanumeric, else, consider escaping it for use in a regex pattern.

The pattern will match a {{...}} substring having no } inside (with {{.*?}}) or (|) it will match and capture the text content ((aTags[index].textContent)) into Group 1. When you get a match, you need to pass 2 arguments to the callback, the whole match and Group 1 value. If Group 1 is not empty, you perform string manipulations, else, just insert the match back.

Upvotes: 0

wp78de
wp78de

Reputation: 18950

We can apply the good old *SKIP what's to avoid approach and throw everything that does not need to be replaced in the full match and capture the desired output in group 1:

{{[^}]+}}|(string)

To make this work effectively in JavaScript we have to use a .replace callback function:

const regex = /{{[^}]+}}|(string)/gm;
const str = `string 
 string  
{{string}}`;

var index = 1; //this is your index var and is somehow set from outside
const result = str.replace(regex, function(m, group1) {
    if (group1) return `{{${index}:${group1}}}`;
    else return m;
});
console.log('Substitution result: ', result);

I had pseudo-coded this a bit since I cannot know where index and aTags[index].textContent is coming from. Adjust as needed.

Upvotes: 2

Related Questions