[英]Extracting capital letters ( English ) | Preferred method
Given a string of text 给出一串文字
var string1 = 'IAmNotFoo';
How do you extract just the capital letters? 你如何只提取大写字母?
'IANF'
Here are some methods per links below: 以下是每个链接的一些方法:
function isUpperCase1(aCharacter) {
if ( ch == ch.toUpperCase() ) {
return true;
}
return false;
}
function isUpperCase2( aCharacter ) {
return ( aCharacter >= 'A' ) && ( aCharacter <= 'Z' );
}
var string1 = 'IAmNotFoo',
string2 = '',
i = 0,
ch = '';
while ( i <= string1.length ) {
ch = string1.charAt( i );
if (!isNaN( ch * 1 ) ) {
alert('character is numeric');
}
else if ( isUpperCase2() ) { // or isUpperCase1
string2 += ch;
}
i++;
}
or simply ( per comment below ): 或简单地(以下评论):
var upper = str.replace(/[^A-Z]/g, '');
SO Related SO相关
Finding uppercase characters within a string 查找字符串中的大写字符
How can I test if a letter in a string is uppercase or lowercase using JavaScript? 如何使用JavaScript测试字符串中的字母是大写还是小写?
I like working with numbers so I would prefer converting to integers and checking the ascii range. 我喜欢使用数字,所以我更喜欢转换为整数并检查ascii范围。 You can see this chart here www.ascii-code.com.
您可以在www.ascii-code.com上看到此图表。
All capital letters have a separate ascii code from their lower case counterparts. 所有大写字母都有一个与小写字母相对应的单独的ascii代码。
do something like this 做这样的事情
String str = "IAmNoFoo";
returnCaps(str);
Public static String returnCaps(String, str)
{
for (int i = 0; i < str.length; i++)
{
int letter = str.convertToInt(charAt(i));
if (letter >= 65 || letter <= 90)
return str.substring.charAt(i);
else
return "No Capital Letters Found"
}
}
You might need to set the loop check to i <= str.length 您可能需要将循环检查设置为i <= str.length
This will check to see if the character at each index of the string is a captial or not. 这将检查字符串的每个索引处的字符是否为captial。 I think it is easiest to think mathematically.
我认为以数学方式思考是最容易的。
With a little tweaking you could very easily make this into a recursive method. 通过一些调整,您可以非常轻松地将其转换为递归方法。
正则表达式方法是迄今为止最简单和最有效的方法,因为它只是一个步骤而不是一个大循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.