如何消除部分字符串并保存到变量中?

时间:2017-07-27 17:45:54

标签: javascript jquery

我有string喜欢:

/wiki/Bologna_Central_Station

我正在尝试将其保存在var中,如下所示:

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

但我只需保存Bologna_Central_Station

6 个答案:

答案 0 :(得分: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);




答案 1 :(得分: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]);




答案 2 :(得分:0)

您可以根据/拆分它,它会为您提供一个数组,您可以从中获取所需的值

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

答案 3 :(得分:0)

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

var string = '/wiki/Bologna_Central_Station'

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

答案 4 :(得分:0)

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

答案 5 :(得分:0)

您也可以使用简单的RegExp执行此操作,并替换任意数量的/



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