简体   繁体   中英

How to get the last before character between two characters from string in javascript?

I need to get the last before character between two characters from string how to do it using javascript. I tried a lot and searched in google I didnt find any answer.

for my example string output is

A26261990L|B26261992S|

by using the below logic I could able to get the 26261990L this output as per my need.

str.split('A').pop().split('|')[0]

I need to fetch "L" and based on two characters "A", "|". as well as "s" based on two characters "B", "|" etc...

How to achieve this functionality.

Like this?

 var str = "A26261990L|B26261992S|"; var splitted = str.split("|"); var item1 = splitted[0]; var item2 = splitted[1]; console.log(item1.charAt(item1.length-1)); console.log(item2.charAt(item2.length-1));

Which fetches the "L" and the "S" in the string

If by "character" you mean letter, then here is a piece of logic that might help you. I'm finding a start and end index of the characters that are passed in, and if it's possible to search, then iterate from end index backwards.

Also, notice str.indexOf(end, startIdx) . It checks for the index of the end character after the index of the start character.

 function between(str, start, end) { const startIdx = str.indexOf(start); // Find end index after start index const endIdx = str.indexOf(end, startIdx); if (startIdx === -1 || endIdx === -1 || startIdx >= endIdx) { // Not specified in the question return "Not found"; } for (let i = endIdx - 1; i > startIdx; i--) { if (str[i] >= "A" && str[i] <= "Z") { return str[i]; } } // Not specified in the question return "Not found"; } const str = "A26261990L|B26261992S|"; console.log(between(str, "A", "|")); console.log(between(str, "B", "|")); console.log(between(str, "C", "|"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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