最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Replace capital letters in an entire string with lowercase letters and hyphens - Stack Overflow

programmeradmin4浏览0评论

I'm trying to replace the capital letters in an entire string with their lower case counter parts while adding hyphen after it (unless its the last letter). So that Sunny&Cloudy would be e sunny-&-cloudy

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

I've tried this this myself but it only reaches the first capital letter adds a hyphen and stops. Leaving me with -S

I'm trying to replace the capital letters in an entire string with their lower case counter parts while adding hyphen after it (unless its the last letter). So that Sunny&Cloudy would be e sunny-&-cloudy

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

I've tried this this myself but it only reaches the first capital letter adds a hyphen and stops. Leaving me with -S

Share Improve this question edited May 29, 2019 at 22:29 WillMac997 asked May 29, 2019 at 21:51 WillMac997WillMac997 1431 gold badge3 silver badges9 bronze badges 9
  • But & is not a capital letter. Why do you want a hypen after it? Why noy sunny-&c-loudy? – GOTO 0 Commented May 29, 2019 at 21:58
  • Which part of your code adds the hyphen? – PM 77-1 Commented May 29, 2019 at 21:58
  • name.toLowerCase().replace(/&/g, "-&-") – Juan Commented May 29, 2019 at 21:59
  • Can you add other examples so we can understand what you need to do in other scenarios? – Shidersz Commented May 29, 2019 at 22:00
  • Hello, can you further explain where do you want to add the hyphen? Would they appear at the end of each word? Will all words have a & in between them? Thanks ! – DiegoTArg Commented May 29, 2019 at 22:01
 |  Show 4 more ments

4 Answers 4

Reset to default 4

If you want to convert Sunny&Cloudy into sunny-&-cloudy, then the following code should work:

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

Basically you just use a function as the second parameter of .replace. (Reference)

It's not only replacing capitalized letter with their lowercase counterpart though, so you might want to revise your question description.

One possible approach for what you need is to use the replacement function of String.replace()

var name = 'Sunny&Cloudy';

let res = name.replace(/[A-Z&]/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;}

You can use word boundaries \b to split the string into tokens, map everything to lowercase (except the last letter) and join the result together with a - dash

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

The following regex should do the trick:

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

By the way regex101. can e in handy to perfect a regex. You can select the 'ECMAScript/JavaScript' regex option. I use that site whenever I need to create a regex.

发布评论

评论列表(0)

  1. 暂无评论