这是一种使用正则表达式和的方法replace
:
var str = /* ... */;
str = str.replace(/^(\/plan\/[^\/]+)\/.*$/, '$1');
这样做:
- 捕获:
/plan
在字符串开头匹配
- ...其次是
/
- ...后跟一个或多个非
/
- 将以下内容匹配
/
到字符串结尾的任何内容
- 将完全匹配替换为第一个捕获组
(如果没有匹配,就没有替代品。)
测试:Live Copy | 资源
var tests = [
{test: "", expect: ""},
{test: "/foo", expect: "/foo"},
{test: "/plan/123", expect: "/plan/123"},
{test: "/plan/123/4567", expect: "/plan/123"},
{test: "/plan/123/4567/89010", expect: "/plan/123"}
];
var index, test, result;
for (index = 0; index < tests.length; ++index) {
test = tests[index];
result = test.test.replace(/^(\/plan\/[^\/]+)\/.*$/, '$1');
if (result === test.expect) {
display("OK: " + test.test + " => " + result);
}
else {
display("FAIL: " + test.test + " => " + result);
}
}
结果:
好的:=>
好的:/foo => /foo
好的:/plan/123 => /plan/123
好的:/plan/123/4567 => /plan/123
好的:/plan/123/4567/89010 => /plan/123