[英]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.我需要从字符串中获取两个字符之间的最后一个字符,如何使用 javascript 进行操作。 I tried a lot and searched in google I didnt find any answer.
我尝试了很多并在谷歌搜索我没有找到任何答案。
for my example string output is对于我的示例字符串 output 是
A26261990L|B26261992S|
by using the below logic I could able to get the 26261990L
this output as per my need.通过使用以下逻辑,我可以根据需要获得
26261990L
这个 output。
str.split('A').pop().split('|')[0]
I need to fetch "L" and based on two characters "A", "|".我需要获取“L”并基于两个字符“A”、“|”。 as well as "s" based on two characters "B", "|"
以及基于两个字符“B”、“|”的“s” etc...
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获取字符串中的“L”和“S”
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)
.另外,请注意
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", "|"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.