JavaScript에서 String.Format 사용?
이것은 나를 미치게 만든다. 똑같은 질문을했지만 더 이상 찾을 수 없습니다 (Stack Overflow 검색, Google 검색을 사용하고 수동으로 게시물을 검색하고 코드를 검색했습니다).
나는 당신이 뭔가를 할 수있는 C # String.Format과 같은 것을 원했습니다.
string format = String.Format("Hi {0}",name);
물론 JavaScript의 경우 한 사람이 간단한 대답을 주었는데 jQuery 플러그인 같은 것이 아니었지만 JSON 같은 것을 만든 것 같고 작동하고 사용하기 쉽습니다.
나는 내 인생을 위해이 게시물을 찾을 수 없습니다.
나는 이것을 내 코드에 가지고 있지만 그것을 사용하는 것을 찾을 수없는 것 같고 몇 번 사용했다고 확신합니다.
String.prototype.format = function(o)
{
return this.replace(/{([^{}]*)}/g,
function(a, b)
{
var r = o[b];
return typeof r === 'string' ? r : a;
}
);
};
MsAjax string 의 코드를 수정하십시오 .
모든 _validateParams
코드를 제거하기 만하면 JavaScript에서 완전한 .NET 문자열 클래스를 사용할 수 있습니다.
좋아, 모든 msajax 종속성을 제거하여 msajax 문자열 클래스를 해제했습니다. 트림 함수, endsWith / startsWith 등을 포함하여 .NET 문자열 클래스와 마찬가지로 훌륭하게 작동합니다.
추신-모든 Visual Studio JavaScript IntelliSense 도우미와 XmlDocs는 그대로 두었습니다. Visual Studio를 사용하지 않는 경우 무해하지만 원하는 경우 제거 할 수 있습니다.
<script src="script/string.js" type="text/javascript"></script>
<script type="text/javascript">
var a = String.format("Hello {0}!", "world");
alert(a);
</script>
String.js
// String.js - liberated from MicrosoftAjax.js on 03/28/10 by Sky Sanders
// permalink: http://stackoverflow.com/a/2534834/2343
/*
Copyright (c) 2009, CodePlex Foundation
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of CodePlex Foundation nor the names of its contributors may be used to endorse or
promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</textarea>
*/
(function(window) {
$type = String;
$type.__typeName = 'String';
$type.__class = true;
$prototype = $type.prototype;
$prototype.endsWith = function String$endsWith(suffix) {
/// <summary>Determines whether the end of this instance matches the specified string.</summary>
/// <param name="suffix" type="String">A string to compare to.</param>
/// <returns type="Boolean">true if suffix matches the end of this instance; otherwise, false.</returns>
return (this.substr(this.length - suffix.length) === suffix);
}
$prototype.startsWith = function String$startsWith(prefix) {
/// <summary >Determines whether the beginning of this instance matches the specified string.</summary>
/// <param name="prefix" type="String">The String to compare.</param>
/// <returns type="Boolean">true if prefix matches the beginning of this string; otherwise, false.</returns>
return (this.substr(0, prefix.length) === prefix);
}
$prototype.trim = function String$trim() {
/// <summary >Removes all leading and trailing white-space characters from the current String object.</summary>
/// <returns type="String">The string that remains after all white-space characters are removed from the start and end of the current String object.</returns>
return this.replace(/^\s+|\s+$/g, '');
}
$prototype.trimEnd = function String$trimEnd() {
/// <summary >Removes all trailing white spaces from the current String object.</summary>
/// <returns type="String">The string that remains after all white-space characters are removed from the end of the current String object.</returns>
return this.replace(/\s+$/, '');
}
$prototype.trimStart = function String$trimStart() {
/// <summary >Removes all leading white spaces from the current String object.</summary>
/// <returns type="String">The string that remains after all white-space characters are removed from the start of the current String object.</returns>
return this.replace(/^\s+/, '');
}
$type.format = function String$format(format, args) {
/// <summary>Replaces the format items in a specified String with the text equivalents of the values of corresponding object instances. The invariant culture will be used to format dates and numbers.</summary>
/// <param name="format" type="String">A format string.</param>
/// <param name="args" parameterArray="true" mayBeNull="true">The objects to format.</param>
/// <returns type="String">A copy of format in which the format items have been replaced by the string equivalent of the corresponding instances of object arguments.</returns>
return String._toFormattedString(false, arguments);
}
$type._toFormattedString = function String$_toFormattedString(useLocale, args) {
var result = '';
var format = args[0];
for (var i = 0; ; ) {
// Find the next opening or closing brace
var open = format.indexOf('{', i);
var close = format.indexOf('}', i);
if ((open < 0) && (close < 0)) {
// Not found: copy the end of the string and break
result += format.slice(i);
break;
}
if ((close > 0) && ((close < open) || (open < 0))) {
if (format.charAt(close + 1) !== '}') {
throw new Error('format stringFormatBraceMismatch');
}
result += format.slice(i, close + 1);
i = close + 2;
continue;
}
// Copy the string before the brace
result += format.slice(i, open);
i = open + 1;
// Check for double braces (which display as one and are not arguments)
if (format.charAt(i) === '{') {
result += '{';
i++;
continue;
}
if (close < 0) throw new Error('format stringFormatBraceMismatch');
// Find the closing brace
// Get the string between the braces, and split it around the ':' (if any)
var brace = format.substring(i, close);
var colonIndex = brace.indexOf(':');
var argNumber = parseInt((colonIndex < 0) ? brace : brace.substring(0, colonIndex), 10) + 1;
if (isNaN(argNumber)) throw new Error('format stringFormatInvalid');
var argFormat = (colonIndex < 0) ? '' : brace.substring(colonIndex + 1);
var arg = args[argNumber];
if (typeof (arg) === "undefined" || arg === null) {
arg = '';
}
// If it has a toFormattedString method, call it. Otherwise, call toString()
if (arg.toFormattedString) {
result += arg.toFormattedString(argFormat);
}
else if (useLocale && arg.localeFormat) {
result += arg.localeFormat(argFormat);
}
else if (arg.format) {
result += arg.format(argFormat);
}
else
result += arg.toString();
i = close + 1;
}
return result;
}
})(window);
여기 내가 사용하는 것이 있습니다. 이 함수는 유틸리티 파일에 정의되어 있습니다.
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;
}
그리고 나는 그것을 이렇게 부릅니다.
var greeting = String.format("Hi, {0}", name);
나는 이것을 어디서 발견했는지 기억하지 못하지만 그것은 나에게 매우 유용했습니다. 구문이 C # 버전과 동일하기 때문에 마음에 듭니다.
다음과 같이 일련의 교체를 수행 할 수 있습니다.
function format(str)
{
for(i = 1; i < arguments.length; i++)
{
str = str.replace('{' + (i - 1) + '}', arguments[i]);
}
return str;
}
더 나은 방법은 함수 매개 변수로 대체를 사용하는 것입니다.
function format(str, obj) {
return str.replace(/\{\s*([^}\s]+)\s*\}/g, function(m, p1, offset, string) {
return obj[p1]
})
}
이렇게하면 인덱스와 명명 된 매개 변수를 모두 제공 할 수 있습니다.
var arr = ['0000', '1111', '2222']
arr.a = 'aaaa'
str = format(" { 0 } , {1}, { 2}, {a}", arr)
// returns 0000 , 1111, 2222, aaaa
타사 기능이없는 경우 :
string format = "Hi {0}".replace('{0}', name)
여러 매개 변수 사용 :
string format = "Hi {0} {1}".replace('{0}', name).replace('{1}', lastname)
다음은 정규 표현식과 캡처를 사용하는 유용한 문자열 형식 지정 함수입니다.
function format (fmtstr) {
var args = Array.prototype.slice.call(arguments, 1);
return fmtstr.replace(/\{(\d+)\}/g, function (match, index) {
return args[index];
});
}
문자열은 C # String.Format과 같은 형식을 지정할 수 있습니다.
var str = format('{0}, {1}!', 'Hello', 'world');
console.log(str); // prints "Hello, world!"
형식은 순서가 맞지 않더라도 올바른 위치에 올바른 변수를 배치합니다.
var str = format('{1}, {0}!', 'Hello', 'world');
console.log(str); // prints "world, Hello!"
도움이 되었기를 바랍니다!
String.Format
.NET Framework의 메서드에는 여러 서명이 있습니다. 내가 가장 좋아 하는 것은 프로토 타입에서 params 키워드를 사용합니다 .
public static string Format(
string format,
params Object[] args
)
이 버전을 사용하면 가변 개수의 인수를 전달할 수있을뿐만 아니라 배열 인수도 전달할 수 있습니다.
Jeremy가 제공하는 간단한 솔루션이 마음에 들기 때문에 조금 확장하고 싶습니다.
var StringHelpers = {
format: function(format, args) {
var i;
if (args instanceof Array) {
for (i = 0; i < args.length; i++) {
format = format.replace(new RegExp('\\{' + i + '\\}', 'gm'), args[i]);
}
return format;
}
for (i = 0; i < arguments.length - 1; i++) {
format = format.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i + 1]);
}
return format;
}
};
이제 String.Format
다음과 같은 방식으로 JavaScript 버전을 사용할 수 있습니다 .
StringHelpers.format("{0}{1}", "a", "b")
과
StringHelpers.format("{0}{1}", ["a", "b"])
@roydukkey의 답변을 기반으로 런타임에 약간 더 최적화되었습니다 (정규식을 캐시합니다).
(function () {
if (!String.prototype.format) {
var regexes = {};
String.prototype.format = function (parameters) {
for (var formatMessage = this, args = arguments, i = args.length; --i >= 0;)
formatMessage = formatMessage.replace(regexes[i] || (regexes[i] = RegExp("\\{" + (i) + "\\}", "gm")), args[i]);
return formatMessage;
};
if (!String.format) {
String.format = function (formatMessage, params) {
for (var args = arguments, i = args.length; --i;)
formatMessage = formatMessage.replace(regexes[i - 1] || (regexes[i - 1] = RegExp("\\{" + (i - 1) + "\\}", "gm")), args[i]);
return formatMessage;
};
}
}
})();
다음은 String.prototype에서만 작동하는 솔루션입니다.
String.prototype.format = function() {
var s = this;
for (var i = 0; i < arguments.length; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i]);
}
return s;
}
이 기능을 만들고 사용하십시오.
function format(str, args) {
for (i = 0; i < args.length; i++)
str = str.replace("{" + i + "}", args[i]);
return str;
}
str 매개 변수 를 변경하지 않으려면 for
루프 전에 새 문자열로 복제 (복제)하고 ( str 의 새 복사본 만들기 ) for
루프에 복사본을 설정하고 마지막에 대신 반환합니다. 매개 변수 자체.
C # (Sharp)에서는 간단히을 호출하여 복사본을 만들 수 String.Clone()
있지만 JavaScript에서는 방법을 모르지만 Google에서 검색하거나 인터넷에서 서핑하고 방법을 배울 수 있습니다.
방금 JavaScript의 문자열 형식에 대한 아이디어를 제공했습니다.
ECMAScript 6에서 템플릿 리터럴 사용 :
var customer = { name: "Foo" }
var card = { amount: 7, product: "Bar", unitprice: 42 }
var message = `Hello ${customer.name},
want to buy ${card.amount} ${card.product} for
a total of ${card.amount * card.unitprice} bucks?`
String 프로토 타입을 수정하고 있다는 사실을 제외하고는 제공 한 함수에 문제가 없습니다. 사용하는 방법은 다음과 같습니다.
"Hello {0},".format(["Bob"]);
독립형 함수로 원하면 다음과 같이 약간 변경할 수 있습니다.
function format(string, object) {
return string.replace(/{([^{}]*)}/g,
function(match, group_match)
{
var data = object[group_match];
return typeof data === 'string' ? data : match;
}
);
}
Vittore의 방법도 좋습니다. 그의 함수는 각 추가 형식화 옵션이 인수로 전달되는 동안 호출되며, 당신은 객체를 기대합니다.
이것이 실제로 보이는 것은 John Resig의 마이크로 템플릿 엔진 입니다.
함수는 이미 JSON 객체를 매개 변수로 사용합니다.
string format = "Hi {foo}".replace({
"foo": "bar",
"fizz": "buzz"
});
눈치 채면 코드 :
var r = o[b];
매개 변수 (o)를보고 그 안에있는 키-값 쌍을 사용하여 "교체"를 해결합니다.
다음은 프로토 타입 및 기능 옵션을 모두 허용하는 솔루션입니다.
// --------------------------------------------------------------------
// Add prototype for 'String.format' which is c# equivalent
//
// String.format("{0} i{2}a night{1}", "This", "mare", "s ");
// "{0} i{2}a night{1}".format("This", "mare", "s ");
// --------------------------------------------------------------------
if(!String.format)
String.format = function(){
for (var i = 0, args = arguments; i < args.length - 1; i++)
args[0] = args[0].replace("{" + i + "}", args[i + 1]);
return args[0];
};
if(!String.prototype.format && String.format)
String.prototype.format = function(){
var args = Array.prototype.slice.call(arguments).reverse();
args.push(this);
return String.format.apply(this, args.reverse())
};
즐겨.
방금 Java String.format()
를 JavaScript로 이식하기 시작했습니다 . 유용 할 수도 있습니다.
It supports basic stuff like this:
StringFormat.format("Hi %s, I like %s", ["Rob", "icecream"]);
Which results in
Hi Rob, I like icecream.
But also more advanced numberic formatting and date formatting like:
StringFormat.format("Duke's Birthday: %1$tA %1$te %1$tB, %1$tY", [new Date("2014-12-16")]);
Duke's Birthday: Tuesday 16 December, 2014
See for more in the examples.
See here: https://github.com/RobAu/javascript.string.format
if (!String.prototype.format) {
String.prototype.format = function () {
var args = arguments;
return this.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}
Usage:
'{0}-{1}'.format('a','b');
// Result: 'a-b'
//Add "format" method to the string class
//supports: "Welcome {0}. You are the first person named {0}".format("David");
// and "First Name:{} Last name:{}".format("David","Wazy");
// and "Value:{} size:{0} shape:{1} weight:{}".format(value, size, shape, weight)
String.prototype.format = function () {
var content = this;
for (var i = 0; i < arguments.length; i++) {
var target = '{' + i + '}';
content=content.split(target).join(String(arguments[i]))
content = content.replace("{}", String(arguments[i]));
}
return content;
}
alert("I {} this is what {2} want and {} works for {2}!".format("hope","it","you"))
You can mix and match using positional and "named" replacement locations using this function.
Here are my two cents:
function stringFormat(str) {
if (str !== undefined && str !== null) {
str = String(str);
if (str.trim() !== "") {
var args = arguments;
return str.replace(/(\{[^}]+\})/g, function(match) {
var n = +match.slice(1, -1);
if (n >= 0 && n < args.length - 1) {
var a = args[n + 1];
return (a !== undefined && a !== null) ? String(a) : "";
}
return match;
});
}
}
return "";
}
alert(stringFormat("{1}, {0}. You're looking {2} today.",
"Dave", "Hello", Math.random() > 0.5 ? "well" : "good"));
Use sprintf library
Here you have a link where you can find the features of this library.
String.prototype.format = function () {
var formatted = this;
for (var arg in arguments) {
formatted = formatted.split('{' + arg + '}').join(arguments[arg]);
}
return formatted;
};
USAGE:
'Hello {0}!'.format('Word')
->
Hello World!
'He{0}{0}o World!'.format('l')
->
Hello World!
'{0} {1}!'.format('Hello', 'Word')
->
Hello World!
'{0}!'.format('Hello {1}', 'Word')
->
Hello World!
참고URL : https://stackoverflow.com/questions/2534803/use-of-string-format-in-javascript
'Nice programing' 카테고리의 다른 글
그래프의 Y 축에 대한 매력적인 선형 스케일 선택 (0) | 2020.10.29 |
---|---|
JavaScript로 모든 쿠키를 삭제하려면 어떻게해야합니까? (0) | 2020.10.28 |
ASP.NET MVC 전역 변수 (0) | 2020.10.28 |
산란 용 matplotlib 컬러 바 (0) | 2020.10.28 |
편집 텍스트 커서 색상 변경 (0) | 2020.10.28 |