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.

6
  • 1
    "#f1groupId#f1:#f1vb2E8F#f1v".replace(/#f1v(.*)#f1v/, "#f1vOther#f1v") Commented Jul 4, 2018 at 20:44
  • 2
    Possible duplicate of How to replace all occurrences of a string in JavaScript? Commented Jul 4, 2018 at 20:49
  • Totally different question @chris g Commented Jul 5, 2018 at 4: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. Commented Jul 5, 2018 at 7: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. Commented Jul 5, 2018 at 10:57

2 Answers 2

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.

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

2 Comments

Thanks Raj!! I was close, but did the .* Part wrong
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!
0

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

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.