字符串中的大写字母 [英] Alternate capitalisation in a string

查看:93
本文介绍了字符串中的大写字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个替换字母大写的函数.例如,Hello World将变为HeLlO wOrLd.字符串的第一个字母必须始终大写.

I would like to create a function which alternates letter capitalisation. For example, Hello World would become HeLlO wOrLd. The first letter of the string must always be capitalised.

这是我编写的代码:

function alternatingCaps(str) {
    let alternate = str.charAt(0).toUpperCase();
    for(let i = 1; i < str.length; i++) {
        let previousChar = str.charAt(i - 1);
        if(previousChar === previousChar.toUpperCase())
            alternate += str.charAt(i).toLowerCase();
        else if(previousChar === previousChar.toLowerCase())
            alternate += str.charAt(i).toUpperCase();
    }
    return alternate;
}

我用提供的字符串的首字母大写声明了alternate变量.然后,我遍历字符串的其余部分,并检查当前迭代之前的字符是大写还是小写;无论哪种情况,当前字母都将变为相反.

I declared the alternate variable with the capitalised first character of the supplied string. I then loop through the rest of the string and check if the character preceding the current iteration is uppercase or lowercase; whichever it is, the current letter will become the opposite.

但是,这没有理想的结果.这是一些测试及其相应的结果:

However, this does not have the desired outcome. Here are a couple of tests and their corresponding results:

console.log(alternatingCaps('hello world'));
// Output: "HELLO wORLD"

console.log(alternatingCaps('jAvaScrIPT ruLEZ'));
// Output: "JAvAScRIpt rULez"

如何修复我的功能?

推荐答案

let s = 'hello there this is a test';
s = s.split('').map( (letter,i) => (i % 2) == 0 ?  letter.toUpperCase() : letter.toLowerCase() ).join('')
console.log( s );

更新:如果您想忽略但保留空格,那么这是另一种解决方案,尽管有些棘手.它不仅会忽略空格,而且还会对与正则表达式匹配的字母进行操作.

Update: if you want to ignore but preserve the spaces, then here is another solution, albeit a little screwy. It doesn't just ignore spaces, it only operates on letters matching the regular expression.

let s = 'hello there this is a test';
let ul = false;
s = s.split('').map(letter => letter.match(/[a-zA-Z]/) != null ? (ul = ! ul, ul ? letter.toUpperCase() : letter.toLowerCase()) : letter).join('');
console.log( s );

这篇关于字符串中的大写字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆