Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用正则表达式替换Javascript字符串_Javascript_Regex - Fatal编程技术网

使用正则表达式替换Javascript字符串

使用正则表达式替换Javascript字符串,javascript,regex,Javascript,Regex,给出以下字符串: http://foobar.com/trusted/123/views/AnalyticsInc ..其中123将是一个介于0和9999999之间的数字,我需要能够用不同的值动态替换所述值 我认为最好的方法是使用某种正则表达式模式来替换string.replace,因为“/trusted/”和“/views/”将始终围绕需要交换的值 var foo='http://foobar.com/trusted/123/views/AnalyticsInc'; var newvalue=

给出以下字符串:

http://foobar.com/trusted/123/views/AnalyticsInc

..其中123将是一个介于0和9999999之间的数字,我需要能够用不同的值动态替换所述值

我认为最好的方法是使用某种正则表达式模式来替换string.replace,因为“/trusted/”和“/views/”将始终围绕需要交换的值

var foo='http://foobar.com/trusted/123/views/AnalyticsInc';
var newvalue=654321;
magic(); //magic happens here
console.log(foo); //returns http://foobar.com/trusted/654321/views/...etc

但是我的雷格士功夫太弱了,我无法打败一只小猫。有人能帮我一下吗?或者如果有更好的方法,我很乐意学习。谢谢

它将替换
foo
字符串中从0到9999999的第一个数字:

foo = foo.replace(/\d{1,7}/, newvalue);

演示:

先生,这太完美了。谢谢。更通用的是(
/\/\d+\/,'/'+newvalue+'/')
,因此要替换的数字字符串可以是介于
/
之间的一个或多个数字。