你好在这里挣扎的人..Javascript替换
是否有可能在第一个正斜杠之间用“”替换任何东西,但保留其余部分?
例如变种会
string "/anything-here-this-needs-to-be-replaced123/but-keep-this";
最终会像这样
string "/but-keep-this";
。希望取得SENCE
你好在这里挣扎的人..Javascript替换
是否有可能在第一个正斜杠之间用“”替换任何东西,但保留其余部分?
例如变种会
string "/anything-here-this-needs-to-be-replaced123/but-keep-this";
最终会像这样
string "/but-keep-this";
。希望取得SENCE
你可以简单地使用`lastIndexOf`就一定要得到的只是最后一个斜线/
var str = "/anything-here-this-needs-to-be-replaced123/but-keep-this";
var myarray = str.split('/');
alert('/' . myarray[2]);
像这样:
var string = "/anything-here-this-needs-to-be-replaced123/but-keep-this";
string = string.substring(string.indexOf('/', 1));
You can view a demo here to play with,该.indexOf()
method带有一个可选的第二个参数,说从哪里开始搜索,只需使用即可在这里。
如果你想删除所有斜线开头(从例子不清楚),改变它有点.lastIndexOf()
没有开始的说法,这样的:
var string = "/anything-here-this-needs-to-be-replaced123/but-keep-this";
string = string.substring(string.lastIndexOf('/'));
You can play with that here,效果是一样的例如,但在更多斜杠的情况下会有所不同。
更好的分流(我假设他解析道) – nico 2010-06-12 12:02:40
@nico - 我不知道关于这个(模棱两可的例子)...我重新阅读了这个问题,并且在你评论时已经添加了它:) – 2010-06-12 12:04:37
var s = "/anything-here-this-needs-to-be-replaced123/but-keep-this";
pos = s.lastIndexOf("/");
var s2 = s.substring(pos);
alert(s2);
这没有OP预期的输出'“/ but-keep-this”',尽量不要使用'.split()'为'.substring()'做了什么:) :) – 2010-06-12 12:21:26
@Nick Craver:它确实:http://jsbin.com/ifabe3。你说得对'substring'可能是一条路。 OP可能会考虑那些有这个答案的人,如果这不能解决他正在做的事情。 – Sarfraz 2010-06-12 12:25:00
@Sarfraz - '“/ but-keep-this”!=“but-keep-this”'',我的观点是你缺少斜线:) – 2010-06-12 12:27:15