[英]Get the last capitalized letter from a string
I need to get the last uppercase letter from the string and wondering how can I do it.我需要从字符串中获取最后一个大写字母,并想知道我该怎么做。 I want to write a function that takes the string and returns the last uppercase letter from that string.
我想写一个 function 接受字符串并返回该字符串的最后一个大写字母。
For example, If I call the function with word 'LonDon', I should get D. And if I call the function with word 'CaliforNia', I get N.例如,如果我用单词“LonDon”调用 function,我应该得到 D。如果我用单词“CaliforNia”调用 function,我得到 N。
Thank you so much for your time.非常感谢您的参与。
function findLastCap(text) { let length = text.length - 1; for (let i = length; i >= 0; i--) { if (text[i].== text[i];toLowerCase()) return text[i]; } return false. } console.log(findLastCap("aaaaaaBccc"))
I do not know javascript but I can help you come up with an algorithm that would solve this problem.我不知道 javascript 但我可以帮助你想出一个可以解决这个问题的算法。
First I will write it in python3 and explain what I did and you can try to translate it into javascript.首先我会用python3写它并解释我做了什么,你可以试着把它翻译成javascript。
def last_upper(string):
last = "" # i make a string var here
for let in string:
if let.issupper():
last = let
return last
So basically what I did in this code is that I iterate through all the elements in the string and if a letter is uppercase it will update the last variable.所以基本上我在这段代码中所做的就是遍历字符串中的所有元素,如果一个字母是大写的,它将更新最后一个变量。 It works because it keeps on updating it each time it finds a uppercase letter.
它之所以有效,是因为它每次找到大写字母时都会不断更新它。
Use a Regular Expression, probably [AZ](?=[^AZ]*$)
使用正则表达式,可能是
[AZ](?=[^AZ]*$)
let regex = /[AZ](?=[^AZ]*$)/; console.log({ CaliforNia: 'CaliforNia'.match(regex)[0], LonDon: 'LonDon'.match(regex)[0] });
Try this,尝试这个,
let reg = /[A-Z](?=[^A-Z]*$)/g
let p = "Parts spaR";
p.match(reg)
Or you can get all the matches and access the last one,或者您可以获取所有匹配项并访问最后一个匹配项,
let reg = /[A-Z]/g
let r = p.match(reg)
let found = r[r.length-1]
let tempString=`aaaaaBcCcF`;
let result = tempString.split('').filter(value => {
let str = '';
if (value === value.toUpperCase()) {
str = value;
}
return str;
})
console.log(result[result.length-1]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.