"camelCase"를 "Camel Case"로 변환하는 방법?
내가 좋아하는 뭔가를 설정하는 자바 스크립트 정규식 명령을 얻기 위해 노력했습니다 "thisString"
에 "This String"
내가 가까이서 보는이 같은 결과 편지를 대체하지만, "Thi String"
또는 "This tring"
. 어떤 아이디어?
문자를 대문자로 표기하는 단순성을 처리 할 수 있음을 명확히하기 위해 RegEx만큼 강력하지는 않지만 문제가있는 곳 "somethingLikeThis"
으로 나눕니다 "something Like This"
.
"thisStringIsGood"
// insert a space before all caps
.replace(/([A-Z])/g, ' $1')
// uppercase the first character
.replace(/^./, function(str){ return str.toUpperCase(); })
표시
This String Is Good
(function() {
var $textbox = $('#textbox'),
$result = $('#result'),
splitter = function() {
$result.html($textbox.val()
// insert a space before all caps
.replace(/([A-Z])/g, ' $1')
// uppercase the first character
.replace(/^./, function(str) {
return str.toUpperCase();
}));
};
$textbox.on('input', splitter);
splitter();
}());
#result {
margin-top: 10px;
padding-top: 10px;
border-top: solid 1px #c3c3c3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Text to split
<input id="textbox" value="thisStringIsGood" />
</div>
<div id="result"></div>
특히 xmlHTTPRequest와 같은 일련의 대문자를 처리하는 데 유휴 관심이있었습니다. 나열된 함수는 "Xml HTTP Request"또는 "Xml HTTPRequest"를 생성하고, "Xml HTTP Request"를 생성합니다.
function unCamelCase (str){
return str
// insert a space between lower & upper
.replace(/([a-z])([A-Z])/g, '$1 $2')
// space before last upper in a sequence followed by lower
.replace(/\b([A-Z]+)([A-Z])([a-z])/, '$1 $2$3')
// uppercase the first character
.replace(/^./, function(str){ return str.toUpperCase(); })
}
gist 에는 String.prototype 버전도 있습니다 .
This can be concisely done with regex lookahead (live demo):
function splitCamelCaseToString(s) {
return s.split(/(?=[A-Z])/).join(' ');
}
(I thought that the g
(global) flag was necessary, but oddly enough, it isn't in this particular case.)
Using lookahead with split
ensures that the matched capital letter is not consumed and avoids dealing with a leading space if UpperCamelCase is something you need to deal with. To capitalize the first letter of each, you can use:
function splitCamelCaseToString(s) {
return s.split(/(?=[A-Z])/).map(function(p) {
return p.charAt(0).toUpperCase() + p.slice(1);
}).join(' ');
}
The map
array method is an ES5 feature, but you can still use it in older browsers with some code from MDC. Alternatively, you can iterate over the array elements using a for
loop.
I think this should be able to handle consecutive uppercase characters as well as simple camelCase.
For example: someVariable => someVariable, but ABCCode != A B C Code.
The below regex works on your example but also the common example of representing abbreviations in camcelCase.
"somethingLikeThis"
.replace(/([a-z])([A-Z])/g, '$1 $2')
.replace(/([A-Z])([a-z])/g, ' $1$2')
.replace(/\ +/g, ' ') => "something Like This"
"someVariableWithABCCode"
.replace(/([a-z])([A-Z])/g, '$1 $2')
.replace(/([A-Z])([a-z])/g, ' $1$2')
.replace(/\ +/g, ' ') => "some Variable With ABC Code"
You could also adjust as above to capitalize the first character.
function spacecamel(s){
return s.replace(/([a-z])([A-Z])/g, '$1 $2');
}
spacecamel('somethingLikeThis')
// returned value: something Like This
Lodash handles this nicely with _.startCase()
A solution that handles numbers as well:
function capSplit(str){
return str.replace
( /(^[a-z]+)|[0-9]+|[A-Z][a-z]+|[A-Z]+(?=[A-Z][a-z]|[0-9])/g
, function(match, first){
if (first) match = match[0].toUpperCase() + match.substr(1);
return match + ' ';
}
)
}
Tested here [JSFiddle, no library. Not tried IE]; should be pretty stable.
If you don't care about older browsers (or don't mind using a fallback reduce function for them), this can split even strings like 'xmlHTTPRequest' (but certainly the likes of 'XMLHTTPRequest' cannot).
function splitCamelCase(str) {
return str.split(/(?=[A-Z])/)
.reduce(function(p, c, i) {
if (c.length === 1) {
if (i === 0) {
p.push(c);
} else {
var last = p.pop(), ending = last.slice(-1);
if (ending === ending.toLowerCase()) {
p.push(last);
p.push(c);
} else {
p.push(last + c);
}
}
} else {
p.push(c.charAt(0).toUpperCase() + c.slice(1));
}
return p;
}, [])
.join(' ');
}
My version
function camelToSpace (txt) {
return txt
.replace(/([^A-Z]*)([A-Z]*)([A-Z])([^A-Z]*)/g, '$1 $2 $3$4')
.replace(/ +/g, ' ')
}
camelToSpace("camelToSpaceWithTLAStuff") //=> "camel To Space With TLA Stuff"
Try this solution here -
var value = "myCamelCaseText";
var newStr = '';
for (var i = 0; i < value.length; i++) {
if (value.charAt(i) === value.charAt(i).toUpperCase()) {
newStr = newStr + ' ' + value.charAt(i)
} else {
(i == 0) ? (newStr += value.charAt(i).toUpperCase()) : (newStr += value.charAt(i));
}
}
return newStr;
Not regex, but useful to know plain old techniques like this.
var origString = "thisString";
var newString = origString.charAt(0).toUpperCase() + origString.substring(1);
참고URL : https://stackoverflow.com/questions/4149276/how-to-convert-camelcase-to-camel-case
'Programming' 카테고리의 다른 글
예 / 아니요 입력과 같은 APT 명령 행 인터페이스? (0) | 2020.06.08 |
---|---|
서클 C에서 com.android.tools.build:gradle:3.0.0-alpha1을 찾을 수 없습니다. (0) | 2020.06.08 |
애니메이션없이 활동 전환 (0) | 2020.06.08 |
문자열에 포함-대소 문자 무시 (0) | 2020.06.08 |
Virtualenv 명령을 찾을 수 없음 (0) | 2020.06.08 |