簡體   English   中英

使用RegEx更改大小寫,其中字符串中可能有數字

[英]Change case with RegEx where there may be numbers in the string

我有此功能將字符串轉換為標題大小寫,

export function toTitleCase(text) {
  const result = text.replace(/([A-Z])/g, ' $1');
  return result.charAt(0).toUpperCase() + result.slice(1);
}

使用camelCase的結果是Camel Case。 結果是正確的。

使用camel23Case的結果是Camel23 Case。
我希望結果是Camel 23 Case

使用camelCASE的結果是Camel CASE。
我希望結果是Camel CASE。

查找大寫字母或數字的序列,並在它們之前添加一個空格。 然后將第一個小寫字母替換為大寫版本:

 const toTitleCase = (text) => text .replace(/([AZ]+|[0-9]+)/g, ' $1') .replace(/\\b([az])/g, (m) => m.toUpperCase()); console.log(toTitleCase('camelCase')); console.log(toTitleCase('camel23Case')); console.log(toTitleCase('camelCASE')); 

試試這個正則表達式- /((?<=[az])[0-9A-Z])|(?<=[a-z0-9])[AZ]/g

function toTitleCase(text) {
  var regex = /((?<=[a-z])[0-9A-Z])|(?<=[a-z0-9])[A-Z]/g;
  const result = text.replace( regex, function(m){ return " " + m });
  return result.charAt(0).toUpperCase() + result.slice(1);
}

演示

 function toTitleCase(text) { var regex = /((?<=[az])[0-9A-Z])|(?<=[a-z0-9])[AZ]/g; const result = text.replace(regex, function(m) { return " " + m }); return result.charAt(0).toUpperCase() + result.slice(1); } console.log(toTitleCase("camel23Case")); console.log(toTitleCase("camel23CASE")); 

說明

  • ((?<=[az])[0-9A-Z])匹配以下大寫字母或字符,如果前一個字符是小寫字母

  • (?<=[a-z0-9])[AZ]僅在前一個字符是小寫字母或數字時才匹配后一個字母。

暫無
暫無

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

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