0

How do I search a string in Javascript for all instances of [SM_g]randomword[SM_h]. and replace them all with [SM_g]randomword.[SM_h].

I'd also like to do this with commas. For example - I need to be able to turn [SM_g]randomword[SM_h], into [SM_g]randomword,[SM_h].

Here is my code so far:

const periodRegex = /\[SM_g](.*?)\[SM_h](?:[.])/g;
string_afterregex - string_initial.replace(periodRegex, /*I don't know what goes in here*/)

2 Answers 2

1

Capture the patterns and then reorder with back reference:

const periodRegex = /(\[SM_g].*?)(\[SM_h])([.,])/g;

var string_initial = '[SM_g]randomword[SM_h].'
var string_afterregex = string_initial.replace(periodRegex, "$1$3$2");
console.log(string_afterregex);

var string_initial = '[SM_g]randomword[SM_h],'
console.log(string_initial.replace(periodRegex, "$1$3$2"))

Sign up to request clarification or add additional context in comments.

2 Comments

Your answer did not quite work because it turned [SM_g]randomword[SM_h]. into [SM_g]randomword.[SM_h]. instead of [SM_g]randomword.[SM_h] However, I figured out that by changing your regex to /(\[SM_g].*?)(\[SM_h])([.])/g then I would have the solution. If you want to update your solution, I can mark it as correct.
Sorry, I didn't read your question very carefully first time. I guess you want to move the trailing . or , after the randomword instead of simply inserting a character.
0

You don't have to use multiple regexes to achieve what you want if you benefit from lookaheads:

const re = /\[SM_g](?=(((?:(?!\[SM_h]).)*)\[SM_h])([.,]))\1./g;
const str = '[SM_g]$2$3[SM_h]';

console.log("[SM_g]WORD[SM_h], [SM_g]WORD[SM_h]. [SM_g]WORD[SM_h]".replace(re, str));

Breakdown:

  • \[SM_g] Match [SM_g] literally
  • (?= Start of a positive lookahead
    • ( Start of capturing group #1
      • ( Start of CG #2
        • (?: Start of NCG #1, tempered dot
          • (?!\[SM_h]). Match next character without skipping over a [SM_h]
        • )* End of NCG #1, repeat as much as possible
      • ) End of CG #2
      • \[SM_h] Match [SM_h] literally
    • ) End of CG #2
    • ( Start of CG #3
      • [.,] Match a comma or a period
    • ) End of CG #4
  • ) End of positive lookahead
  • \1. Match what's matched by CG #1 then a character

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.