Debian Codegraph @

dojo/string.js

raw symbols SCIP
1 define([
2 "./_base/kernel", // kernel.global
3 "./_base/lang"
4 ], function(kernel, lang){
5
6 // module:
7 // dojo/string
8 var ESCAPE_REGEXP = /[&<>'"\/]/g;
9 var ESCAPE_MAP = {
10 '&': '&amp;',
11 '<': '&lt;',
12 '>': '&gt;',
13 '"': '&quot;',
14 "'": '&#x27;',
15 '/': '&#x2F;'
16 };
17 var string = {
18 // summary:
19 // String utilities for Dojo
20 };
21 lang.setObject("dojo.string", string);
22
23 string.escape = function(/*String*/str){
24 // summary:
25 // Efficiently escape a string for insertion into HTML (innerHTML or attributes), replacing &, <, >, ", ', and / characters.
26 // str:
27 // the string to escape
28 if(!str){ return ""; }
29 return str.replace(ESCAPE_REGEXP, function(c) {
30 return ESCAPE_MAP[c];
31 });
32 };
33
34 // Adapted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt#Polyfill
35 string.codePointAt = String.prototype.codePointAt ?
36 function (str, position) {
37 return String.prototype.codePointAt.call(str, position);
38 } :
39 function(str, position) {
40 if (str == null) {
41 throw new TypeError('codePointAt called on null or undefined');
42 }
43
44 var size;
45 var first;
46 var second;
47 var index;
48
49 str = String(str);
50 size = str.length;
51 // `ToInteger`
52 index = position ? Number(position) : 0;
53
54 if (index != index) { // better `isNaN`
55 index = 0;
56 }
57
58 // Account for out-of-bounds indices:
59 if (index < 0 || index >= size) {
60 return undefined;
61 }
62
63 // Get the first code unit
64 first = str.charCodeAt(index);
65
66 // check if it's the start of a surrogate pair
67 if (first >= 0xD800 && first <= 0xDBFF && // high surrogate
68 size > index + 1 // there is a next code unit
69 ) {
70 second = str.charCodeAt(index + 1);
71 if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
72 // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
73 return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
74 }
75 }
76
77 return first;
78 };
79
80 // Adapted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint#Polyfill
81 string.fromCodePoint = String.fromCodePoint || function () {
82 var codeUnits = [];
83 var codeLen = 0;
84 var result = "";
85 var codePoint;
86 var index;
87
88 for (index = 0, len = arguments.length; index !== len; ++index) {
89 codePoint = +arguments[index];
90 // correctly handles all cases including `NaN`, `-Infinity`, `+Infinity`
91 // The surrounding `!(...)` is required to correctly handle `NaN` cases
92 // The (codePoint>>>0) === codePoint clause handles decimals and negatives
93 if (!(codePoint < 0x10FFFF && (codePoint>>>0) === codePoint)) {
94 throw RangeError("Invalid code point: " + codePoint);
95 }
96
97 if (codePoint <= 0xFFFF) { // BMP code point
98 codeLen = codeUnits.push(codePoint);
99 } else { // Astral code point; split in surrogate halves
100 // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
101 codePoint -= 0x10000;
102 codeLen = codeUnits.push(
103 (codePoint >> 10) + 0xD800, // highSurrogate
104 (codePoint % 0x400) + 0xDC00 // lowSurrogate
105 );
106 }
107
108 if (codeLen >= 0x3fff) {
109 result += String.fromCharCode.apply(null, codeUnits);
110 codeUnits.length = 0;
111 }
112 }
113
114 return result + String.fromCharCode.apply(null, codeUnits);
115 };
116
117 string.rep = function(/*String*/str, /*Integer*/num){
118 // summary:
119 // Efficiently replicate a string `n` times.
120 // str:
121 // the string to replicate
122 // num:
123 // number of times to replicate the string
124
125 if(num <= 0 || !str){ return ""; }
126
127 var buf = [];
128 for(;;){
129 if(num & 1){
130 buf.push(str);
131 }
132 if(!(num >>= 1)){ break; }
133 str += str;
134 }
135 return buf.join(""); // String
136 };
137
138 string.pad = function(/*String*/text, /*Integer*/size, /*String?*/ch, /*Boolean?*/end){
139 // summary:
140 // Pad a string to guarantee that it is at least `size` length by
141 // filling with the character `ch` at either the start or end of the
142 // string. Pads at the start, by default.
143 // text:
144 // the string to pad
145 // size:
146 // length to provide padding
147 // ch:
148 // character to pad, defaults to '0'
149 // end:
150 // adds padding at the end if true, otherwise pads at start
151 // example:
152 // | // Fill the string to length 10 with "+" characters on the right. Yields "Dojo++++++".
153 // | string.pad("Dojo", 10, "+", true);
154
155 if(!ch){
156 ch = '0';
157 }
158 var out = String(text),
159 pad = string.rep(ch, Math.ceil((size - out.length) / ch.length));
160 return end ? out + pad : pad + out; // String
161 };
162
163 string.substitute = function( /*String*/ template,
164 /*Object|Array*/map,
165 /*Function?*/ transform,
166 /*Object?*/ thisObject){
167 // summary:
168 // Performs parameterized substitutions on a string. Throws an
169 // exception if any parameter is unmatched.
170 // template:
171 // a string with expressions in the form `${key}` to be replaced or
172 // `${key:format}` which specifies a format function. keys are case-sensitive.
173 // The special sequence `${}` can be used escape `$`.
174 // map:
175 // hash to search for substitutions
176 // transform:
177 // a function to process all parameters before substitution takes
178 // place, e.g. mylib.encodeXML
179 // thisObject:
180 // where to look for optional format function; default to the global
181 // namespace
182 // example:
183 // Substitutes two expressions in a string from an Array or Object
184 // | // returns "File 'foo.html' is not found in directory '/temp'."
185 // | // by providing substitution data in an Array
186 // | string.substitute(
187 // | "File '${0}' is not found in directory '${1}'.",
188 // | ["foo.html","/temp"]
189 // | );
190 // |
191 // | // also returns "File 'foo.html' is not found in directory '/temp'."
192 // | // but provides substitution data in an Object structure. Dotted
193 // | // notation may be used to traverse the structure.
194 // | string.substitute(
195 // | "File '${name}' is not found in directory '${info.dir}'.",
196 // | { name: "foo.html", info: { dir: "/temp" } }
197 // | );
198 // example:
199 // Use a transform function to modify the values:
200 // | // returns "file 'foo.html' is not found in directory '/temp'."
201 // | string.substitute(
202 // | "${0} is not found in ${1}.",
203 // | ["foo.html","/temp"],
204 // | function(str){
205 // | // try to figure out the type
206 // | var prefix = (str.charAt(0) == "/") ? "directory": "file";
207 // | return prefix + " '" + str + "'";
208 // | }
209 // | );
210 // example:
211 // Use a formatter
212 // | // returns "thinger -- howdy"
213 // | string.substitute(
214 // | "${0:postfix}", ["thinger"], null, {
215 // | postfix: function(value, key){
216 // | return value + " -- howdy";
217 // | }
218 // | }
219 // | );
220
221 thisObject = thisObject || kernel.global;
222 transform = transform ?
223 lang.hitch(thisObject, transform) : function(v){ return v; };
224
225 return template.replace(/\$\{([^\s\:\}]*)(?:\:([^\s\:\}]+))?\}/g,
226 function(match, key, format){
227 if (key == ''){
228 return '$';
229 }
230 var value = lang.getObject(key, false, map);
231 if(format){
232 value = lang.getObject(format, false, thisObject).call(thisObject, value, key);
233 }
234 var result = transform(value, key);
235
236 if (typeof result === 'undefined') {
237 throw new Error('string.substitute could not find key "' + key + '" in template');
238 }
239
240 return result.toString();
241 }); // String
242 };
243
244 string.trim = String.prototype.trim ?
245 lang.trim : // aliasing to the native function
246 function(str){
247 str = str.replace(/^\s+/, '');
248 for(var i = str.length - 1; i >= 0; i--){
249 if(/\S/.test(str.charAt(i))){
250 str = str.substring(0, i + 1);
251 break;
252 }
253 }
254 return str;
255 };
256
257 /*=====
258 string.trim = function(str){
259 // summary:
260 // Trims whitespace from both sides of the string
261 // str: String
262 // String to be trimmed
263 // returns: String
264 // Returns the trimmed string
265 // description:
266 // This version of trim() was taken from [Steven Levithan's blog](http://blog.stevenlevithan.com/archives/faster-trim-javascript).
267 // The short yet performant version of this function is dojo/_base/lang.trim(),
268 // which is part of Dojo base. Uses String.prototype.trim instead, if available.
269 return ""; // String
270 };
271 =====*/
272
273 return string;
274 });