Paul Fabbroni
Paul Fabbroni

Reputation: 123

How to replace the value of a string within a string in javascript

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.

Upvotes: 0

Views: 77

Answers (2)

Paul Fabbroni
Paul Fabbroni

Reputation: 123

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

Upvotes: 0

Raj Kumar
Raj Kumar

Reputation: 65

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.

Upvotes: 2

Related Questions