3 回答

TA貢獻1829條經驗 獲得超7個贊
您可以將該.replace()
方法與正則表達式一起使用。首先,您可以使用.toUpperCase()
. 然后,你可以匹配中間的所有字符,(
并)
使用該replace
方法的替換功能將匹配到的字符轉換為小寫。
請參見下面的示例:
function uppercase(str) {
return str.toUpperCase().replace(/\(.*?\)/g, function(m) {
return m.toLowerCase();
});
}
console.log(uppercase("(H)e(L)lo")); // (h)E(l)LO
console.log(uppercase("(H)ELLO (W)orld")); // (h)ELLO (w)ORLD
如果你可以支持 ES6,你可以用箭頭函數清理上面的函數:
const uppercase = str =>
str.toUpperCase().replace(/\(.*?\)/g, m => m.toLowerCase());
console.log(uppercase("(H)e(L)lo")); // (h)E(l)LO
console.log(uppercase("(H)ELLO (W)orld")); // (h)ELLO (w)ORLD

TA貢獻1807條經驗 獲得超9個贊
我試圖在不使用任何正則表達式的情況下做到這一點。我正在存儲 all(和的索引)。
String.prototype.replaceBetween = function (start, end, what) {
return this.substring(0, start) + what + this.substring(end);
};
function changeCase(str) {
str = str.toLowerCase();
let startIndex = str.split('').map((el, index) => (el === '(') ? index : null).filter(el => el !== null);
let endIndex = str.split('').map((el, index) => (el === ')') ? index : null).filter(el => el !== null);
Array.from(Array(startIndex.length + 1).keys()).forEach(index => {
if (index !== startIndex.length) {
let indsideParentheses = '(' + str.substring(startIndex[index] + 1, endIndex[index]).toUpperCase() + ')';
str = str.replaceBetween(startIndex[index], endIndex[index] + 1, indsideParentheses);
}
});
return str;
}
let str = '(h)ELLO (w)ORLD'
console.log(changeCase(str));
添加回答
舉報