简体   繁体   English

如何在javascript中的字符串中替换字符串的值

[英]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". 假设我有一个类似于以下“#f1groupId#f1:#f1vb2E8F#f1v”的字符串。 How do I replace everything between the first "#f1v" and the second "#f1v" with the word "Other" for example. 例如,如何用单词“其他”替换第一个“#f1v”和第二个“#f1v”之间的所有内容。 i know how to do it with indexOf and substrings, but I was looking for a smarter way to do it. 我知道如何使用indexOf和子字符串,但是我一直在寻找一种更智能的方法。 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. 我问如何替换具有给定开始标记和结束标记,但介于两者之间的动态字符串的动态字符串。

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. 希望对您有帮助。

"#f1groupId#f1:#f1vb2E8F#f1v".replace(/#f1v(.*)#f1v/, "#f1vOther#f1v") did the trick. “#f1groupId#f1:#f1vb2E8F#f1v” .replace(/#f1v(。*)#f1v /,“#f1vOther#f1v”)达到了目的。 Thank-you @Juvian! 谢谢@朱维安!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM