0

Trying to figure out a Regex to inject and remove a string (in this case var.par_) at the following locations:

  • Very Beginning
  • After ^
  • After ^OR

Example input string when injecting:

job=developer^language=js^ORlanguage=react^ORlanguageSTARTSWITHjava

Should result in output of

var.par_job=developer^var.par_language=js^ORvar.par_language=react^ORvar.par_languageSTARTSWITHjava

and vice versa when removing:

var.par_language=react^ORvar.par_languageSTARTSWITHjava

should result in

language=react^ORlanguageSTARTSWITHjava

My current feeble attempt was this:

var input = "job=developer^language=js^ORlanguage=react^ORlanguageSTARTSWITHjava";


const replaceToken = "var.par_";


var output = input.replace(/^()?/, replaceToken).replace(/\^()?/g, '^' + replaceToken);
Seth Duncan
  • 1,231
  • 1
  • 13
  • 31
  • StackOverflow is not a free coding service. You're expected to [try to solve the problem first](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users). Please update your question to show what you have already tried in a [mcve]. For further information, please see [ask], and take the [tour] :) – Barmar Sep 02 '20 at 21:53
  • You can match those locations with `(^|\^OR|\^)` – Barmar Sep 02 '20 at 21:57
  • Added my current attempt barman – Seth Duncan Sep 02 '20 at 22:27
  • What's the point of the empty group `()?` – Barmar Sep 02 '20 at 22:29

1 Answers1

1

let input = "job=developer^language=js^ORlanguage=react^ORlanguageSTARTSWITHjava";
const replaceToken = "var.par_";
let output = input.replace(/^|\^OR|\^/g, '$&' + replaceToken);
console.log(output)

The regexp /^|\^OR|\^/ matches each of your locations. $& in the replacement gets replaced with the match. So there's no need to use multiple calls to .replace().

Barmar
  • 596,455
  • 48
  • 393
  • 495
  • Honestly I thought I tried that combo with the pipe and was getting no luck. Maybe it was an errant typo, but thank you. Also I called you the incorrect name, so I apologize. – Seth Duncan Sep 02 '20 at 22:38
  • You're not the first. But there's automatic name completion after `@`, you should use that. – Barmar Sep 02 '20 at 22:40