用javascript替换字符串的一部分? [英] Replacing part of a string with javascript?
问题描述
假设我有一个看起来像这样的网址:
Let's say I have a URL that looks something like this:
http://www.mywebsite.com/param1:set1/param2:set2/param3:set3/
我在javascript中使它变得可变但现在我想将param2:set2更改为param2:set5或随你。我如何抓住字符串的那一部分并进行更改?
I've made it a varaible in my javascript but now I want to change "param2:set2" to be "param2:set5" or whatever. How do I grab that part of the string and change it?
需要注意的一点是字符串中的param2 ...可以改变以及:后面的字符数。我知道我可以使用substring从前面获取字符串的一部分,但我不知道如何从末尾或中间的任何地方抓取它。
One thing to note is where "param2..." is in the string can change as well as the number of characters after the ":". I know I can use substring to get part of the string from the front but I'm not sure how to grab it from the end or anywhere in the middle.
推荐答案
这个怎么样?
>>> var url = 'http://www.mywebsite.com/param1:set1/param2:set2/param3:set3/';
>>> url.replace(/param2:[^/]+/i, 'param2:set5');
"http://www.mywebsite.com/param1:set1/param2:set5/param3:set3/"
这篇关于用javascript替换字符串的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!