admin管理员组

文章数量:1400188

I'm trying to capitalize every letter after a / or - character. Meaning, if given the string

this/is/a/pretty-cool/url

Its expected output would look like

This/Is/A/Pretty-Cool/Url

My code:

string = string.replace(/\/(\b[a-z](?!\s))/g, function(i,e) { return '/'+e.toUpperCase() });

Which currently returns

this/Is/A/Pretty-cool/Url

Not quite there, obviously.

How can I get this to work as expected?

I'm trying to capitalize every letter after a / or - character. Meaning, if given the string

this/is/a/pretty-cool/url

Its expected output would look like

This/Is/A/Pretty-Cool/Url

My code:

string = string.replace(/\/(\b[a-z](?!\s))/g, function(i,e) { return '/'+e.toUpperCase() });

Which currently returns

this/Is/A/Pretty-cool/Url

Not quite there, obviously.

How can I get this to work as expected?

Share Improve this question edited Jan 5, 2017 at 19:48 Denys Séguret 383k90 gold badges811 silver badges776 bronze badges asked Jan 5, 2017 at 16:34 ModelesqModelesq 5,42220 gold badges63 silver badges89 bronze badges 1
  • 1 your problem statement is inplete - you also appear to want to capitalise the first character found. – Alnitak Commented Jan 5, 2017 at 16:37
Add a ment  | 

3 Answers 3

Reset to default 10

Here you have a simple solution:

string = string.replace(/(^|\/|-)(\S)/g, s=>s.toUpperCase())

You just match one character after either the start of the string, a / or a -. It's simple because there's no problem uppercasing one of those chars ('/'.toUpperCase() is '/').

Now, let's imagine that you don't want to uppercase the first part (maybe it's different in your real problem, maybe you care about that poor function which has to uppercase a "/"), then you would have used submatches like this:

string = string.replace(/(^|\/|-)(\S)/g, (_,a,b)=>a+b.toUpperCase())

(but you don't have to go to such extremities here)

Starting from your code you have missing the - char.

So, changing the code to support the char you can use:

var string = string.replace(/(^|\/|-)(\b[a-z](?!\s))/g, function(i,e) { return i.charAt(0)+e.toUpperCase() });

or

var string = string.replace(/(^|\/|-)(\b[a-z](?!\s))/g, function(i,e) { return i.toUpperCase() });

Here's another variant, which uppercases after any non-word character, and also at the start of the string:

string = string.replace(/(^|\W)(\w)/g, (match, a, b) => a + b.toUpperCase());

(or using the same short cut as @DenysSéguret):

string = string.replace(/(^|\W)(\w)/g, s => s.toUpperCase());

本文标签: javascriptCapitalize every letter afterandcharactersStack Overflow