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
3 Answers
Reset to default 10Here 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
版权声明:本文标题:javascript - Capitalize every letter afterand - characters - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744239858a2596737.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论