0

Let's say I have a string like the following "#f1groupId#f1:#f1vb2E8F#f1v". How do I replace everything between the first "#f1v" and the second "#f1v" with the word "Other" for example. i know how to do it with indexOf and substrings, but I was looking for a smarter way to do it. Maybe with regex?

This isn't a duplicate of that question because I didn't ask how to replace all occurrences of a string within another string. I asked how to replace a dynamic string that has a given start tag and end tag, but a dynamic string in between.

Paul Fabbroni
  • 123
  • 3
  • 13
  • 1
    "#f1groupId#f1:#f1vb2E8F#f1v".replace(/#f1v(.*)#f1v/, "#f1vOther#f1v") – juvian Jul 04 '18 at 20:44
  • 2
    Possible duplicate of [How to replace all occurrences of a string in JavaScript?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) –  Jul 04 '18 at 20:49
  • Totally different question @chris g – Paul Fabbroni Jul 05 '18 at 04:04
  • @PaulFabbroni You didn't say anything about "dynamic". Doesn't matter though; that question has several answers which explain at length the various method you can use. While it's not a 100% perfect duplicate, everything you need is in there. –  Jul 05 '18 at 07:35
  • It's pretty obvious that's a dynamic string (and I said "like the following" meaning similar to), but yes I should have said dynamic. I did an extensive search and didn't find my answer which is confirmed by the fact that the answer provided here does not match any of the ones I found. – Paul Fabbroni Jul 05 '18 at 10:57
  • P.s. everything I need is not in there. I obviously know about the replace function and as I stated in my question I knew I could use regex but I'm not good with regex and needed the exact regex to use, which was provided below. Thanks to that user for the answer - I will accept it after I test it out. – Paul Fabbroni Jul 05 '18 at 11:06

2 Answers2

2

You can try something like this :

<script>
var a ='#f1groupId#f1:#f1vb2E8F#f1v';
a = a.replace(/f1v.*f1v/, 'f1votherf1v')
</script>

I hope it will help you.

Raj Kumar
  • 65
  • 1
  • 8
  • Thanks Raj!! I was close, but did the .* Part wrong – Paul Fabbroni Jul 05 '18 at 11:07
  • using your answer you forgot the # at the end, you would need a = a.replace(/f1v.*f1v/, 'f1vother#f1v'), but to ensure I grabbed the tags properly juvian's answer above is probabyl the best. Thanks so much for the help though! – Paul Fabbroni Jul 05 '18 at 14:01
0

"#f1groupId#f1:#f1vb2E8F#f1v".replace(/#f1v(.*)#f1v/, "#f1vOther#f1v") did the trick. Thank-you @Juvian!

Paul Fabbroni
  • 123
  • 3
  • 13