PageRenderTime 8ms CodeModel.GetById 2ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 0ms

/ajax/scripts/string.js

http://showslow.googlecode.com/
JavaScript | 43 lines | 35 code | 4 blank | 4 comment | 12 complexity | eab924c496db6ca14cf8a8fb495a7a1e MD5 | raw file
 1/*==================================================
 2 *  String Utility Functions and Constants
 3 *==================================================
 4 */
 5
 6String.prototype.trim = function() {
 7    return this.replace(/^\s+|\s+$/g, '');
 8};
 9
10String.prototype.startsWith = function(prefix) {
11    return this.length >= prefix.length && this.substr(0, prefix.length) == prefix;
12};
13
14String.prototype.endsWith = function(suffix) {
15    return this.length >= suffix.length && this.substr(this.length - suffix.length) == suffix;
16};
17
18String.substitute = function(s, objects) {
19    var result = "";
20    var start = 0;
21    while (start < s.length - 1) {
22        var percent = s.indexOf("%", start);
23        if (percent < 0 || percent == s.length - 1) {
24            break;
25        } else if (percent > start && s.charAt(percent - 1) == "\\") {
26            result += s.substring(start, percent - 1) + "%";
27            start = percent + 1;
28        } else {
29            var n = parseInt(s.charAt(percent + 1));
30            if (isNaN(n) || n >= objects.length) {
31                result += s.substring(start, percent + 2);
32            } else {
33                result += s.substring(start, percent) + objects[n].toString();
34            }
35            start = percent + 2;
36        }
37    }
38    
39    if (start < s.length) {
40        result += s.substring(start);
41    }
42    return result;
43};