![](/img/trans.png)
[英]How do I replace a character between the last occurrence of two characters in a string in JavaScript?
[英]How to get the last before character between two characters from string in javascript?
我需要從字符串中獲取兩個字符之間的最后一個字符,如何使用 javascript 進行操作。 我嘗試了很多並在谷歌搜索我沒有找到任何答案。
對於我的示例字符串 output 是
A26261990L|B26261992S|
通過使用以下邏輯,我可以根據需要獲得26261990L
這個 output。
str.split('A').pop().split('|')[0]
我需要獲取“L”並基於兩個字符“A”、“|”。 以及基於兩個字符“B”、“|”的“s” ETC...
如何實現這個功能。
像這樣?
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));
獲取字符串中的“L”和“S”
如果“字符”是指字母,那么這里有一個可能對您有所幫助的邏輯。 我正在查找傳入字符的開始和結束索引,如果可以搜索,則從結束索引向后迭代。
另外,請注意str.indexOf(end, startIdx)
。 它在開始字符的索引之后檢查結束字符的索引。
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.