从MsAjax字符串中适应代码。
只需删除所有_validateParams
代码,就可以实现在JavaScript中完整的.NET字符串类。
好的,我解放了msajax字符串类,删除了所有msajax依赖项。它像.NET字符串类一样完美地工作,包括修剪函数、endsWith / startsWith等。
P.S. - 我保留了所有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
(function(window) {
$type = String;
$type.__typeName = 'String';
$type.__class = true;
$prototype = $type.prototype;
$prototype.endsWith = function String$endsWith(suffix) {
return (this.substr(this.length - suffix.length) === suffix);
}
$prototype.startsWith = function String$startsWith(prefix) {
return (this.substr(0, prefix.length) === prefix);
}
$prototype.trim = function String$trim() {
return this.replace(/^\s+|\s+$/g, '');
}
$prototype.trimEnd = function String$trimEnd() {
return this.replace(/\s+$/, '');
}
$prototype.trimStart = function String$trimStart() {
return this.replace(/^\s+/, '');
}
$type.format = function String$format(format, args) {
return String._toFormattedString(false, arguments);
}
$type._toFormattedString = function String$_toFormattedString(useLocale, args) {
var result = '';
var format = args[0];
for (var i = 0; ; ) {
var open = format.indexOf('{', i);
var close = format.indexOf('}', i);
if ((open < 0) && (close < 0)) {
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;
}
result += format.slice(i, open);
i = open + 1;
if (format.charAt(i) === '{') {
result += '{';
i++;
continue;
}
if (close < 0) throw new Error('format stringFormatBraceMismatch');
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 (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);