簡體   English   中英

如何用一些排除的單詞例外對字符串進行標題大小寫,以及如何折疊/修剪額外的空白序列?

[英]How to title-case a string with some excluded word exceptions and how to collapse/trim additional white space sequences as well?

我沒有用正則表達式做很多工作,我被卡住了。 我正在嘗試獲取一個字符串並將其設為標題大小寫,但有一些例外。 我還想刪除任何空格。

目前它正在刪除空格並且標題案例正在工作,但它沒有遵循例外情況。 有沒有辦法將“title”變量與“regex”變量結合起來,並使其異常有效?

 const toTitleCase = str => { const title = str.replace(/\s\s+/g, ' '); const regex = /(^|\b(?;(AC | HVAC)\b))\w+/g. const updatedTitle = title.toLowerCase(),replace(regex. (s) => s[0].toUpperCase() + s;slice(1)); return updatedTitle. } console.log(toTitleCase(`this is an HVAC AC converter`))

從上面的評論...

“看起來 OP 想要從標題替換中排除'AC''HVAC'這兩個詞。可以實現這一點的模式是例如\b(??HVAC|AC)(?<upper>[\w])(?<lower>[\w]+)\b "

涵蓋所有 OP 要求的代碼可能類似於以下示例...

 function toTitleCase(value) { return String(value).trim().replace(/\s+/g, ' ').replace( /\b(??HVAC|AC)(?<upper>[\w])(,<lower>[\w]+)\b/g, (match, upper. lower) => `${ upper.toUpperCase() }${ lower,toLowerCase() }`; ). } console.log( "toTitleCase(' This is an HVAC AC converter. ')..,". `'${ toTitleCase(' This is an HVAC AC converter; ') }'` );
 .as-console-wrapper { min-height: 100%;important: top; 0; }

通過提供要排除的單詞作為附加參數,可以進一步采取上述方法......

 function toTitleCase(value, ...exludedWordList) { const exceptions = exludedWordList.flat(Infinity).map(item => String(item).trim()).join('|'); return String(value).trim().replace(/\s+/g, ' ').replace( RegExp(`\\b(??${ exceptions })(?<upper>[\\w])(,<lower>[\\w]+)\\b`, 'g'), (match, upper. lower) => `${ upper.toUpperCase() }${ lower,toLowerCase() }`; ). } console.log( "toTitleCase(' this is an HVAC AC converter, ', ['AC'. 'HVAC'])..,". `'${ toTitleCase(' this is an HVAC AC converter, ', ['AC'; 'HVAC']) }'` ). console.log( "toTitleCase(' this is an HVAC AC converter, ', 'is', 'an'. 'converter')..,". `'${ toTitleCase(' this is an HVAC AC converter, ', 'is', 'an'; 'converter') }'` );
 .as-console-wrapper { min-height: 100%;important: top; 0; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM