简体   繁体   English

如何从以“ |”分隔的字符串中获取最后一个文本

[英]how to take last text from a string separated by “|”

I am having a string same like 我有一个像

a|b|c|d|e|....|n

I need to get the last item in this string in javascript. 我需要在javascript中获取此字符串中的最后一项。 There may be n number of items in this string. 此字符串中可能有n个项目。 Thanks in advance. 提前致谢。

yourString.split('|').slice(-1)[0]

A bit verbose but probably the most straightforward way: 有点冗长,但可能是最直接的方法:

var str = 'a|b|c|e|f';
var arr = str.split('|'); // split into array
alert(arr[arr.length-1]); // get last element of the array

If your string is very long, you will want to avoid using .split('|') since that will create a new array with potentially many elements. 如果您的字符串很长,则将避免使用.split('|')因为这将创建一个可能包含许多元素的新数组。 I like .split('|') because it's unambiguous what you're trying to do, but if you want efficiency, you can use: 我喜欢.split('|')因为它可以清晰地表示您要执行的操作,但是如果您想提高效率,可以使用:

yourString.substr(yourString.lastIndexOf('|')+1)

(This will even work in corner cases like "abc" , "abc|" , and "|abc" , since lastIndexOf returns -1 if nothing is found.) (这甚至在"abc""abc|""|abc"极端情况下也可以使用,因为如果找不到任何内容,则lastIndexOf返回-1。)

var str = "a|b|c|d|e|f|g";

var arr = str.split("|");
var last_item = arr[arr.length-1];

现在换个完全不同的东西!

/(?:\||^)([^|]*)$/.exec(str)[1]

Try it...... 试试吧......

str='asfd|asdf|as|df|as|asdf|asf';
str.split('|').slice(b.length-1)[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM