亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將 () 中的任何字母設為小寫,將所有其他字母設為大寫

將 () 中的任何字母設為小寫,將所有其他字母設為大寫

茅侃侃 2022-12-29 15:17:58
我正在嘗試使可變字符串大寫, () 內的字母小寫。字符串將是用戶輸入的內容,所以不知道它會提前。用戶輸入示例輸入了什么(H)e(L)lo 預期結果是什么(h)E(l)LO 輸入了什么(H)ELLO (W)orld 預期結果是什么(h)ELLO (w)ORLD 這是我嘗試過的方法,但只有在 () 位于字符串末尾時才能讓它工作。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。我之前用一個 () 問過一個類似的問題,但現在我們期望字符串中有多個 () 。
查看完整描述

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


查看完整回答
反對 回復 2022-12-29
?
函數式編程

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));


查看完整回答
反對 回復 2022-12-29
?
一只萌萌小番薯

TA貢獻1795條經驗 獲得超7個贊

以防萬一您想要更快的正則表達式替代方案,您可以使用否定字符 ( ^)) 正則表達式而不是惰性 ( ?)。它更快,因為它不需要回溯。

const uppercase = str => 
    str.toUpperCase().replace(/\([^)]+\)/g, m => m.toLowerCase());


查看完整回答
反對 回復 2022-12-29
  • 3 回答
  • 0 關注
  • 127 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號