gpt4 book ai didi

javascript - 如何消除正则表达式代码中的空格?

转载 作者:行者123 更新时间:2023-12-04 08:01:07 25 4
gpt4 key购买 nike

我正在尝试在我的作业中使用正则表达式。
这里有2个问题我无法解决:
问题 1:第一个 if 语句是为了将字符串放入“pascal”大小写。第二个 if 语句进入“ Camel ”案例。不管语句如何,在第一个语句之后执行似乎停止了。我在这里做错了什么?
问题 2:即使返回结果(“pascal”),我的第一个 if 语句我也不知道如何去除代码的正则表达式部分中的空格。
请帮忙。连续第二天卡住了。

const makeCase = function(input, type) {
//place your code here

let inType = type;
let finalInput = (type === inType)


if(finalInput) {
return input.replace(/^(.)|\s+(.)/g, function(str){
return str.toUpperCase();
});
} else if(finalInput) {
return input.replace(/\W+(.)/g, function(str){
return str.toUpperCase();
});
}
};

console.log(makeCase("this is a string", "pascal"));
console.log(makeCase("this is a string", "camel"));


最佳答案

也许做 ucwords,然后删除空格,然后根据类型,大写或小写第一个字符。

function makeCase(str, type) {
str = (str + '').replace(/^([a-z])|\s+([a-z])/g, $1 => $1.toUpperCase()).replace(/ /g, '')
return str.charAt(0)[type === 'pascal' ? 'toUpperCase' : 'toLowerCase']() + str.slice(1)
}

console.log(makeCase("this is a string", "pascal")); // ThisIsAString
console.log(makeCase("this is a string", "camel")); // thisIsAString

关于javascript - 如何消除正则表达式代码中的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66462883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com