String과 동등합니다.jQuery 형식
JavaScript 코드를 MicrosoftAjax에서 JQuery로 이동하려고 합니다.일반적인 .net 메서드(String 등)의 MicrosoftAjax에서 JavaScript를 사용하고 있습니다.format(), String.starts With() 등입니다.jQuery에는 이와 동등한 것이 있습니까?
ASP 소스 코드참조용으로 NET AJAX를 사용할 수 있습니다.따라서 계속 사용할 부품을 다른 JS 파일에 포함할 수 있습니다.또는 jQuery로 포팅할 수 있습니다.
여기 포맷 기능이 있습니다...
String.format = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}
그리고 여기 끝이 있다.With 와 Starts프로토타입 기능 포함...
String.prototype.endsWith = function (suffix) {
return (this.substr(this.length - suffix.length) === suffix);
}
String.prototype.startsWith = function(prefix) {
return (this.substr(0, prefix.length) === prefix);
}
Josh가 게시한 기능의 더 빠른/단순한(및 프로토타입) 변형입니다.
String.prototype.format = String.prototype.f = function() {
var s = this,
i = arguments.length;
while (i--) {
s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
}
return s;
};
사용방법:
'Added {0} by {1} to your collection'.f(title, artist)
'Your balance is {0} USD'.f(77.7)
제가 이걸 너무 많이 써서 그냥...f, 그러나 보다 상세하게 사용할 수도 있습니다.format.예.'Hello {0}!'.format(name)
위의 함수(Julian Jelfs 제외)의 대부분은 다음 오류를 포함합니다.
js> '{0} {0} {1} {2}'.format(3.14, 'a{2}bc', 'foo');
3.14 3.14 afoobc foo
또는 인수 목록의 끝에서 거꾸로 카운트되는 바리안트의 경우:
js> '{0} {0} {1} {2}'.format(3.14, 'a{0}bc', 'foo');
3.14 3.14 a3.14bc foo
여기 올바른 기능이 있습니다.Julian Jelfs의 코드의 원형 변형입니다. 좀 더 조여봤습니다.
String.prototype.format = function () {
var args = arguments;
return this.replace(/\{(\d+)\}/g, function (m, n) { return args[n]; });
};
다음은 같은 버젼의 조금 더 고급 버전입니다.브레이스를 2배로 하면, 이 버젼을 피할 수 있습니다.
String.prototype.format = function () {
var args = arguments;
return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (m, n) {
if (m == "{{") { return "{"; }
if (m == "}}") { return "}"; }
return args[n];
});
};
이것은 올바르게 동작합니다.
js> '{0} {{0}} {{{0}}} {1} {2}'.format(3.14, 'a{2}bc', 'foo');
3.14 {0} {3.14} a{2}bc foo
여기 Blair Mitchelmore의 또 다른 훌륭한 구현이 있습니다: https://web.archive.org/web/20120315214858/http://blairmitchelmore.com/javascript/string.format
컬렉션 또는 배열을 인수로 사용하는 형식 함수를 만들었습니다.
사용방법:
format("i can speak {language} since i was {age}",{language:'javascript',age:10});
format("i can speak {0} since i was {1}",'javascript',10});
코드:
var format = function (str, col) {
col = typeof col === 'object' ? col : Array.prototype.slice.call(arguments, 1);
return str.replace(/\{\{|\}\}|\{(\w+)\}/g, function (m, n) {
if (m == "{{") { return "{"; }
if (m == "}}") { return "}"; }
return col[n];
});
};
공식 옵션인 jQuery.validator가 있습니다.포맷합니다.
jQuery Validation Plugin 1.6(적어도)과 함께 제공됩니다.
와 매우 유사합니다.String.Format에 기재되어 있습니다.그물.
수정된 링크 편집.
검증 플러그인을 사용하는 경우 다음을 사용할 수 있습니다.
jQuery.validator.format("{0} {1}", "cool", "formatting") = 'cool formatting'
http://docs.jquery.com/Plugins/Validation/jQuery.validator.format#templateargumentargumentN...
Q가 요구하는 것은 아니지만, 비슷한 것을 만들었지만, 번호가 아닌 이름 있는 플레이스 홀더를 사용하고 있습니다.저는 개인적으로 명명된 인수를 선호하며, 그 인수에 대한 인수로 객체를 보냅니다(좀 더 장황하지만 유지하기가 더 쉽습니다).
String.prototype.format = function (args) {
var newStr = this;
for (var key in args) {
newStr = newStr.replace('{' + key + '}', args[key]);
}
return newStr;
}
사용 예를 다음에 나타냅니다.
alert("Hello {name}".format({ name: 'World' }));
EcmaScript 2015(ES6)를 지원하는 최신 브라우저를 사용하여 Template String을 즐길 수 있습니다.형식을 지정하는 대신 변수 값을 직접 입력할 수 있습니다.
var name = "Waleed";
var message = `Hello ${name}!`;
템플릿 문자열은 back-ticks()를 사용하여 작성해야 합니다.
지금까지 제시된 답변 중 한 번 초기화하고 이후 사용을 위해 정규 표현을 저장하기 위해 인클로저를 사용하는 것에 대한 명확한 최적화는 없습니다.
// DBJ.ORG string.format function
// usage: "{0} means 'zero'".format("nula")
// returns: "nula means 'zero'"
// place holders must be in a range 0-99.
// if no argument given for the placeholder,
// no replacement will be done, so
// "oops {99}".format("!")
// returns the input
// same placeholders will be all replaced
// with the same argument :
// "oops {0}{0}".format("!","?")
// returns "oops !!"
//
if ("function" != typeof "".format)
// add format() if one does not exist already
String.prototype.format = (function() {
var rx1 = /\{(\d|\d\d)\}/g, rx2 = /\d+/ ;
return function() {
var args = arguments;
return this.replace(rx1, function($0) {
var idx = 1 * $0.match(rx2)[0];
return args[idx] !== undefined ? args[idx] : (args[idx] === "" ? "" : $0);
});
}
}());
alert("{0},{0},{{0}}!".format("{X}"));
또한 이미 존재하는 경우 format() 구현에 관한 예는 없습니다.
늦은 시즌을 훨씬 지났지만, 나는 그저 주어진 답을 보고 나의 가치를 가지고 있다:
사용방법:
var one = strFormat('"{0}" is not {1}', 'aalert', 'defined');
var two = strFormat('{0} {0} {1} {2}', 3.14, 'a{2}bc', 'foo');
방법:
function strFormat() {
var args = Array.prototype.slice.call(arguments, 1);
return arguments[0].replace(/\{(\d+)\}/g, function (match, index) {
return args[index];
});
}
결과:
"aalert" is not defined
3.14 3.14 a{2}bc foo
여기 제 것이 있습니다.
String.format = function(tokenised){
var args = arguments;
return tokenised.replace(/{[0-9]}/g, function(matched){
matched = matched.replace(/[{}]/g, "");
return args[parseInt(matched)+1];
});
}
방탄은 아니지만 현명하게 사용한다면 효과가 있다.
var w = "the Word";
var num1 = 2;
var num2 = 3;
var long_multiline_string = `This is very long
multiline templete string. Putting somthing here:
${w}
I can even use expresion interpolation:
Two add three = ${num1 + num2}
or use Tagged template literals
You need to enclose string with the back-tick (\` \`)`;
console.log(long_multiline_string);
여기 '{'를 탈출하여 할당되지 않은 플레이스 홀더를 정리할 수 있는 내 버전이 있습니다.
function getStringFormatPlaceHolderRegEx(placeHolderIndex) {
return new RegExp('({)?\\{' + placeHolderIndex + '\\}(?!})', 'gm')
}
function cleanStringFormatResult(txt) {
if (txt == null) return "";
return txt.replace(getStringFormatPlaceHolderRegEx("\\d+"), "");
}
String.prototype.format = function () {
var txt = this.toString();
for (var i = 0; i < arguments.length; i++) {
var exp = getStringFormatPlaceHolderRegEx(i);
txt = txt.replace(exp, (arguments[i] == null ? "" : arguments[i]));
}
return cleanStringFormatResult(txt);
}
String.format = function () {
var s = arguments[0];
if (s == null) return "";
for (var i = 0; i < arguments.length - 1; i++) {
var reg = getStringFormatPlaceHolderRegEx(i);
s = s.replace(reg, (arguments[i + 1] == null ? "" : arguments[i + 1]));
}
return cleanStringFormatResult(s);
}
다음 답변이 가장 효율적일 수 있지만 인수의 1 대 1 매핑에만 적합하다는 주의사항이 있습니다.이것은 문자열을 연결하는 가장 빠른 방법을 사용합니다(String Builder와 유사: 문자열 배열, 결합).이건 나만의 암호야더 나은 분리기가 필요하겠지만요
String.format = function(str, args)
{
var t = str.split('~');
var sb = [t[0]];
for(var i = 0; i < args.length; i++){
sb.push(args[i]);
sb.push(t[i+1]);
}
return sb.join("");
}
사용방법:
alert(String.format("<a href='~'>~</a>", ["one", "two"]));
이는 DRY 원칙에 위배되지만 다음과 같은 간단한 해결책입니다.
var button = '<a href="{link}" class="btn">{text}</a>';
button = button.replace('{text}','Authorize on GitHub').replace('{link}', authorizeUrl);
<html>
<body>
<script type="text/javascript">
var str="http://xyz.html?ID={0}&TId={1}&STId={2}&RId={3},14,480,3,38";
document.write(FormatString(str));
function FormatString(str) {
var args = str.split(',');
for (var i = 0; i < args.length; i++) {
var reg = new RegExp("\\{" + i + "\\}", "");
args[0]=args[0].replace(reg, args [i+1]);
}
return args[0];
}
</script>
</body>
</html>
Josh Stodola의 답변은 들을 수 없었지만, 다음과 같은 답변이 효과가 있었습니다.「 」의 .prototypeChrome 및 Safari에서 완료 (IE, FF, Chrome safari Safari )
String.prototype.format = function() {
var s = this;
if(t.length - 1 != args.length){
alert("String.format(): Incorrect number of arguments");
}
for (var i = 0; i < arguments.length; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i]);
}
return s;
}
s정말로 복제품이 되어야 한다this파괴적인 방법이 되지 않기 위해서요 하지만 꼭 그럴 필요는 없어요
adam 확장위의 JLev의 훌륭한 답변은 다음과 같습니다.
// Extending String prototype
interface String {
format(...params: any[]): string;
}
// Variable number of params, mimicking C# params keyword
// params type is set to any so consumer can pass number
// or string, might be a better way to constraint types to
// string and number only using generic?
String.prototype.format = function (...params: any[]) {
var s = this,
i = params.length;
while (i--) {
s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), params[i]);
}
return s;
};
현악기 프로토타입에 추가할 수 있는 플런커가 있습니다.포맷은 다른 예시와 같이 짧을 뿐만 아니라 훨씬 더 유연합니다.
사용 방법은 c# 버전과 유사합니다.
var str2 = "Meet you on {0}, ask for {1}";
var result2 = str2.format("Friday", "Suzy");
//result: Meet you on Friday, ask for Suzy
//NB: also accepts an array
또한 이름 및 객체 속성 사용 지원 추가
var str1 = "Meet you on {day}, ask for {Person}";
var result1 = str1.format({day: "Thursday", person: "Frank"});
//result: Meet you on Thursday, ask for Frank
이와 같은 대체를 사용하여 배열을 닫을 수도 있습니다.
var url = '/getElement/_/_/_'.replace(/_/g, (_ => this.ar[this.i++]).bind({ar: ["invoice", "id", 1337],i: 0}))
> '/getElement/invoice/id/1337
'어느 정도'를 시험해 .bind
'/getElement/_/_/_'.replace(/_/g, (function(_) {return this.ar[this.i++];}).bind({ar: ["invoice", "id", 1337],i: 0}))
// Regex cache
_stringFormatRegex = null;
//
/// Formats values from {0} to {9}. Usage: stringFormat( 'Hello {0}', 'World' );
stringFormat = function () {
if (!_stringFormatRegex) {
// Initialize
_stringFormatRegex = [];
for (var i = 0; i < 10; i++) {
_stringFormatRegex[i] = new RegExp("\\{" + i + "\\}", "gm");
}
}
if (arguments) {
var s = arguments[0];
if (s) {
var L = arguments.length;
if (1 < L) {
var r = _stringFormatRegex;
for (var i = 0; i < L - 1; i++) {
var reg = r[i];
s = s.replace(reg, arguments[i + 1]);
}
}
}
return s;
}
}
언급URL : https://stackoverflow.com/questions/1038746/equivalent-of-string-format-in-jquery
'source' 카테고리의 다른 글
| Java NIO: IOException이란 무엇입니까?끊어진 파이프는? (0) | 2022.12.01 |
|---|---|
| openjdk-6-jre, openjdk-6-jre-headless, openjdk-6-jre-lib의 차이점 (0) | 2022.12.01 |
| MySQL 오프셋 무한 행 (0) | 2022.12.01 |
| 베스트 프랙티스: PHP Magic 메서드 __set 및 __get (0) | 2022.12.01 |
| JavaScript 변수에 PHP 문자열 전달(및 줄바꿈 이스케이프) (0) | 2022.12.01 |