Home > Software design >  Is there a way I can use regex to replace only part of a match in a file that i'm reading in as
Is there a way I can use regex to replace only part of a match in a file that i'm reading in as

Time:01-06

I'm fairly new to regex and am hoping to replace all instances of the following example strings:

<product-id="1234567"/>

<product-id="5678765"/>

<product-id="9101234"/>

with the following:

<product-id="1234567"></cat-assignment>

<product-id="5678765"></cat-assignment>
  
<product-id="9101234"></cat-assignment>

Basically, I'd like to retain the product id values as they will be dynamic, and simply want to remove the '/' character in '/>' and replace it with '>'

I've tried the following regex as an example, but still can't seem to get the result that I want:

var str = str.replace(/product\-id="(.*?)"\/>/,">$1</cat-assignment>");

results in something like:

 > 1234567 </cat-assignment>

Thank you!

CodePudding user response:

You may use a regex replacement:

var input = "BLAH <product-id=\"1234567\"/> STUFF";
var output = input.replace(/<product-id="(.*?)"\/>/g, "<product-id=\"$1\"></cat-assignment>");
console.log(output);

CodePudding user response:

You can replace every (zero-width) match of the following regular expression with '</cat-assignment>':

(?<=^<product-id="\d{7}">)(?=$)

Demo

The expression can be broken down as follows.

(?<=             # begin positive lookbehind
  ^              # match beginning of string
  <product-id="  # match literal
  \d{7}          # match 7 digits
  ">             # match literal
)                # end positive lookbehind
(?=$)            # positive lookahead asserts string position is
                 # at the end of the string 
  •  Tags:  
  • Related