使字符串中的一个字母小写,而使所有其他字母大写

  • 本文关键字:其他 字符串 一个 javascript
  • 更新时间 :
  • 英文 :


我正在尝试使一个变量字符串大写,并使一个字母小写((。字符串将是用户输入的内容,所以不知道它将是什么。

用户输入示例

输入的内容

hello(K)

的预期结果是什么

HELLO(k)

输入的内容

(K)lear

的预期结果是什么

(k)LEAR

以下是我尝试过的,但只有在((位于字符串末尾时才能使其工作。

if(getElementById("ID")){
var headline = getElementById("ID").getValue();
var headlineUpper = headline.toUpperCase();
var IndexOf = headlineUpper.indexOf("(");
if(IndexOf === -1){
template.getRegionNode("Region").setValue(headlineUpper);
}
else{
var plus = parseInt(IndexOf + 1);
var replacing = headlineUpper[plus];
var lower = replacing.toLowerCase();
var render = headlineUpper.replace(headlineUpper.substring(plus), lower + ")");

getElementById("Region").setValue(render);
}
}

做我们的系统我只能使用香草javascript

您可以使用正则表达式替换,以及从捕获组计算替换的函数。

function convertParenCase(str) {
return str.replace(/^([^(]*)(([^)]*))(.*)/,
(match, g1, g2, g3) => g1.toUpperCase() + g2.toLowerCase() + g3.toUpperCase());
}
console.log(convertParenCase('hello(K)'));
console.log(convertParenCase('(K)lear'));

您可以分别处理字符串的三个部分。

const convert = str => {
let idx = str.indexOf('(');
if(idx === -1){
return str.toUpperCase();
} else {
return str.slice(0, idx).toUpperCase() + str.slice(idx, idx + 3).toLowerCase() + str.slice(idx + 3).toUpperCase();
}
};
console.log(convert('hello(K)'));
console.log(convert('(K)lear'));

使用正则表达式可以轻松完成。

if(getElementById("ID")){
var headline = getElementById("ID").getValue();
var headlineUpper = headline.toUpperCase();
var textInBracket = headlineUpper.match(/(.*)/);
if(textInBracket && textInBracket.length) {
headlineUpper = headlineUpper.replace(textInBracket[0], textInBracket[0].toLowerCase())
}
template.getRegionNode("Region").setValue(headlineUpper);
}
let x = 'hello(K)'
x.toUpperCase().replace(/(.+)/g, x.match(/(.+)/g)[0].toLowerCase())

您可以将所有内容转换为大写,然后使用模式匹配将括号内的字符串替换为小写(有点像黑客(

对于你可能会或可能不会得到括号的情况:

x.toUpperCase().replace(/(.+)/g, (x.match(/(.+)/g)?x.match(/(.+)/g)[0]:"").toLowerCase())

相关内容

最新更新