簡體   English   中英

用小寫字母和連字符替換整個字符串中的大寫字母

[英]Replace capital letters in an entire string with lowercase letters and hyphens

我試圖用小寫的小數部分替換整個字符串中的大寫字母,同時在其后添加連字符(除非最后一個字母)。 這樣, Sunny&Cloudy就會變得sunny-&-cloudy

var name = 'Sunny&Cloudy';
name.replace(/([A-Z])(.*)/, '\L$1');

我自己嘗試過此操作,但只有到達第一個大寫字母時才添加連字符並停止。 留下我-S

如果要將Sunny&Cloudy轉換為sunny-&-cloudy ,則以下代碼應該有效:

var name = 'Sunny&Cloudy';
name.replace(/[A-Z][a-z]*/g, str => '-' + str.toLowerCase() + '-')
  // Convert words to lower case and add hyphens around it (for stuff like "&")
  .replace('--', '-') // remove double hyphens
  .replace(/(^-)|(-$)/g, ''); // remove hyphens at the beginning and the end

基本上,您只是將function用作.replace的第二個參數。 參考

不過,它不僅可以用小寫字母替換大寫字母,因此您可能需要修改問題描述。

一種所需的可能方法是使用String.replace()替換函數

 var name = 'Sunny&Cloudy'; let res = name.replace(/[AZ&]/g, m => m === "&" ? "-and-" : m.toLowerCase()); console.log(res); 
 .as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;} 

您可以使用單詞邊界\\b將字符串拆分為標記,將所有內容映射為小寫字母(最后一個字母除外),然后將結果與-連起來

 function dashed(str, sep) { let words = str.split(sep); return words.map(word => { let left = word.slice(0, -1).toLowerCase(); let lastLetter = word.slice(-1); return `${left}${lastLetter}` }).join('-') } console.log( dashed("Sunny&CloudY&Rainy", /\\b/) ) 

以下正則表達式可以解決問題:

const regex = /(.+?\b)+?/g;
const str = 'Sunny&Cloudy&rainy';
const subst = '$1-';
const result = str.replace(regex, subst);

//make string lowercase + remove last '-'
console.log('Substitution result: ', result.toLowerCase().substring(0, result.length - 1));

順便說一下, regex101.com可以派上用場來完善正則表達式。 您可以選擇“ ECMAScript / JavaScript”正則表達式選項。 每當我需要創建正則表達式時,我都會使用該站點。

暫無
暫無

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

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