admin管理员组文章数量:1394578
I have a Camel case string like this s = 'ThisIsASampleString'
and I want to split into an array using the capital letters as the delimiting point. I am expecting this:
['This', 'Is', 'A', 'Sample', 'String']
Here is what I have done so far
s = "ThisIsASampleString";
var regex = new RegExp('[A-Z]',"g");
var arr = s.split(re);
But this is not giving me the correct result because it removes the matched character. I am getting this array as my result ["his", "s", "", "tring"]
. It has removed all the matched capital letters.
How should I avoid this behavior and keep the matched characters also in my result array?
I have a Camel case string like this s = 'ThisIsASampleString'
and I want to split into an array using the capital letters as the delimiting point. I am expecting this:
['This', 'Is', 'A', 'Sample', 'String']
Here is what I have done so far
s = "ThisIsASampleString";
var regex = new RegExp('[A-Z]',"g");
var arr = s.split(re);
But this is not giving me the correct result because it removes the matched character. I am getting this array as my result ["his", "s", "", "tring"]
. It has removed all the matched capital letters.
How should I avoid this behavior and keep the matched characters also in my result array?
Share Improve this question edited Dec 17, 2016 at 18:47 user663031 asked Dec 17, 2016 at 7:11 EzioEzio 2,9852 gold badges31 silver badges50 bronze badges 2- This is not camel-casing. A camel-cased string would start with a lower-case letter. This is sometimes called "Pascal-casing". – user663031 Commented Dec 17, 2016 at 18:49
- Noted @torazaburo – Ezio Commented Dec 19, 2016 at 6:29
1 Answer
Reset to default 9Your regex would split based on the uppercase but the result array doesn't include the matched value. Instead use positive look-ahead assertion to assert the position.
s = "ThisIsASampleString";
var arr = s.split(/(?=[A-Z])/);
console.log(arr);
Regex explanation here
Or you can use String#match
method instead.
s = "ThisIsASampleString";
var arr = s.match(/[A-Z][^A-Z]*/g);
console.log(arr);
Regex explanation here
本文标签: javascriptSplit a camelCase string with regexStack Overflow
版权声明:本文标题:javascript - Split a camelCase string with regex - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744094188a2589980.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论