2017-07-27 45 views
0

我有一个string,如:如何消除部分字符串并保存到变量中?

/wiki/Bologna_Central_Station 

我想将它保存在一个var这样的:

countryLinks = doSelect("Location").siblings('td').find('a').attr(href); 

但我只需要保存Bologna_Central_Station

+0

所以,你只需要在最后 '/' 的字符串? – Taplar

+0

是的消除'/维基/'基本@Taplar –

回答

0
let pattern = new RegExp('\/wiki\/') 

var string = '/wiki/Bologna_Central_Station' 

var newString = string.replace(pattern, '') 
1

有几种方法做到这一点:

String.replace()会做到这一点:

var s = "/wiki/Bologna_Central_Station"; 
 
console.log(s.replace("/wiki/",""));

或者,String.lastIndexOf()String.substring()为能够处理的/字符的任何量的更动态的解决方案:

var s = "/wiki/Bologna_Central_Station"; 
 

 
// Find the index position of the last "/" in the string 
 
var lastSlash = s.lastIndexOf("/"); 
 

 
// Extract a substring of the original starting at one more than 
 
// the lastSlash position and going to the end of the string 
 
var result = s.substring(lastSlash + 1); 
 

 
// Get the part you want: 
 
console.log(result);

或者,String.split()Array.length处理斜线的任何金额:

var s = "/wiki/Bologna_Central_Station"; 
 

 
// Split on the "/" char and return an array of the parts 
 
var ary = s.split("/"); 
 
console.log(ary); 
 

 
// Get the last elmeent in the array. 
 
// This ensures that it works no matter how many slashes you have 
 
console.log(ary[ary.length-1]);

0

您可以根据/拆分它,让你的数组,从中可以得到所需要的价值

var countryLinks = doSelect("Location").siblings('td').find('a').attr(href); 
countryLinks=countryLinks.split("/")[1]; 
2

只要做一些像'/wiki/Bologna_Central_Station'.split('/').splice(-1).join()。这(不像一些其他的解决方案)的功能与斜杠('/foo/bar/baz/wiki/Bologna_Central_Station'.split('/').splice(-1).join())任意数量

例子:

var last = '/wiki/Bologna_Central_Station'.split('/').splice(-1).join(); 
 
console.log(last); 
 

 
var last2 = '/foo/bar/baz/wiki/Bologna_Central_Station'.split('/').splice(-1).join(); 
 
console.log(last2);

+0

我在考虑拆分,但我在考虑使用pop() – Taplar

0
var segments = "/wiki/Bologna_Central_Station".split('/'); 
console.log(segments[segments.length - 1]); 
0

你也可以做到这一点与一个简单的RegExp并替换任意数量的/

var href = "/wiki/Bologna_Central_Station"; 
 
var countryLinks = href.replace(/.*\//g,''); 
 
console.log(countryLinks);

相关问题