我想将特定索引中的字母转换为大写。
我有一个字符串:
let str = "Dwightschrute";
我可以做到:
let str = "Dwightschrute";
let a = str.slice(0, 6);
console.log(a); //Dwight
let b = (str.slice(6, 7)).toUpperCase();
console.log(b); // S
let c = str.slice(7);
console.log(c);
console.log(a+b+c); //DwightSchrute
或
let str = "Dwightschrute";
str = [...str];
str[6] = str[6].toUpperCase();
console.log(str.join('')); //DwightSchrute
有更好的方法吗?我认为我正在做很多不必要的事情来实现这一目标
答案 0 :(得分:5)
我更喜欢第一个版本,仅不包含中间变量,并且您可以使用方括号表示法代替.slice
函数调用来提取一个字符,看起来很干净:
const str = "Dwightschrute";
const result = str.slice(0, 6) + str[6].toUpperCase() + str.slice(7);
console.log(result); //DwightSchrute
另一种方法是使用一个正则表达式,该正则表达式在6个字符之后匹配一个字符,然后使用替换函数在该字符上调用toUpperCase
,尽管这取决于您是否需要改进:
const str = "Dwightschrute";
const result = str.replace(/(?<=.{6})./, char => char.toUpperCase());
console.log(result); //DwightSchrute
或者,不带任何回避:
const str = "Dwightschrute";
const result = str.replace(/(.{6})(.)/, (_, initial, char) => initial + char.toUpperCase());
console.log(result); //DwightSchrute