0

如何在“#overlay/”之后和“/”之前更改第一个字符之后的字符?

var x = "www.foo.com/#overlay/2/";
x.replace(/#overlay\/([^]*)\//, "1"); // i'm expecting: www.foo.com/#overlay/1/

我正在使用此代码,但没有成功。我对正则表达式不太了解。

我搜索了一些问题,但没有成功。

4

2 回答 2

1

我不会在这里使用正则表达式。你可以只使用.split().

var url, newUrl, peices;

url = 'www.foo.com/#overlay/2/';

// Split the string apart by / 
peices = url.split('/');

// Changing the 3 element in the array to 1, it was originally 2.
peices[2] = 1;

// Let's put it back together...
newUrl = peices.join('/');
于 2013-07-03T15:41:19.700 回答
0

你犯了3个错误:

  • 你换的太多了
  • 您不使用返回的值。replace不改变传递的字符串(字符串是不可变的)但返回一个新的
  • 您忘记在捕获组中精确何时停止(实际上它甚至不必是捕获组)

你可以这样做 :

x = x.replace(/(#overlay\/)[^\/]*\//, "$11/");

$1这里指的是第一个捕获的组,因此您不必在替换字符串中键入它。

例如它改变

"www.foo.com/#overlay/2/rw/we/2345"

进入

"www.foo.com/#overlay/1/rw/we/2345"
于 2013-07-03T15:34:55.040 回答