如何在 jQuery 中拆分字符串并获取最后一个匹配项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13737826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to split a string and get last match in jQuery?
提问by Neel
I have string like this
我有这样的字符串
This is ~test content ~ok ~fine.
This is ~test content ~ok ~fine.
I want to get "fine"
which is after special character ~
and on last position in string using jQuery.
我想使用 jQuery获取"fine"
特殊字符之后~
和字符串中最后一个位置。
回答by Adil
You can use combination of [substring()][1] and [lastIndexOf()][2] to get the last element.
您可以使用 [substring()][1] 和 [lastIndexOf()][2] 的组合来获取最后一个元素。
str = "~test content ~thanks ok ~fine";
strFine =str.substring(str.lastIndexOf('~'));
console.log(strFine );
You can use [split()][4] to convert the string to array and get the element at last index, last index is length of array - 1
as array is zero based index.
您可以使用 [ split()][4] 将字符串转换为数组并获取最后一个索引处的元素,最后一个索引是length of array - 1
数组是基于零的索引。
str = "~test content ~thanks ok ~fine";
arr = str.split('~');
strFile = arr[arr.length-1];
console.log(strFile );
OR, simply call pop on array got after split
或者,只需在拆分后的数组上调用 pop
str = "~test content ~thanks ok ~fine";
console.log(str.split('~').pop());
回答by Niet the Dark Absol
Just use plain JavaScript:
只需使用纯 JavaScript:
var str = "This is ~test content ~thanks ok ~fine";
var parts = str.split("~");
var what_you_want = parts.pop();
// or, non-destructive:
var what_you_want = parts[parts.length-1];