我刚刚完成 this programming challenge on CodeWars :
Write a function
toWeirdCase
that accepts a string, and returns the same string with all even indexed characters in each word upper cased, and all odd indexed characters in each word lower cased. The indexing just explained is zero based, so the zero-ith index is even, therefore that character should be upper cased.
我尝试用正则表达式解决这个问题,然后放弃并简单地使用带有索引的 for
循环。只是为了确认,只要有空格,大写字母的索引就会重置为 0。所以 ThIs Is A CorrEcT AnSwEr
但是 ThIs NOT
,因为每个单词的每个首字母都必须大写。
考虑到这一点,是否有一种方法可以使用正则表达式查找备用(奇数或偶数)索引?在这种情况下,使用 \b
找到单词边界,然后从那里找到每个偶数索引,直到单词结束?
最佳答案
可以借map
将函数应用于每个字符,i
%
2
检测i
是否为奇数,toLowerCase
或 toUpperCase
改变大小写:
function toWeirdCase(str) {
return [].map.call(str, function(char, i) {
return char[i%2 ? 'toLowerCase' : 'toUpperCase']();
}).join('');
}
有多种方法可以在每个空间重置索引。例如,
function toWeirdCase(str) {
var i = 0;
return [].map.call(str, function(char) {
if(char === ' ') i = -1;
return char[i++ % 2 ? 'toLowerCase' : 'toUpperCase']();
}).join('');
}
关于javascript - 用于从单词边界交替索引的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31121834/