move some things out of utils.js into other files
[conkeror.git] / modules / string.js
blobc060809cbd66ec6c416a568bd328873095be75e6
1 /**
2  * (C) Copyright 2004-2007 Shawn Betts
3  * (C) Copyright 2007-2009 John J. Foerch
4  * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
5  *
6  * Use, modification, and distribution are subject to the terms specified in the
7  * COPYING file.
8 **/
10 /**
11  * trim_whitespace removes whitespace from the beginning and end of the
12  * given string.
13  */
14 function trim_whitespace (str) {
15     var tmp = new String(str);
16     return tmp.replace(/^\s+/, "").replace(/\s+$/, "");
20 function shell_quote (str) {
21     var s = str.replace("\"", "\\\"", "g");
22     s = s.replace("$", "\$", "g");
23     return s;
26 /* Like perl's quotemeta. Backslash all non-alphanumerics. */
27 function quotemeta (str) {
28     return str.replace(/([^a-zA-Z0-9])/g, "\\$1");
31 /* Given a list of choices (strings), return a regex which matches any
32    of them*/
33 function choice_regex (choices) {
34     var regex = "(?:" + choices.map(quotemeta).join("|") + ")";
35     return regex;
39 /**
40  * get_shortdoc_string, given a docstring, returns the portion of the
41  * docstring up to the first newline, or the whole docstring.
42  */
43 function get_shortdoc_string (doc) {
44     var shortdoc = null;
45     if (doc != null) {
46         var idx = doc.indexOf("\n");
47         if (idx >= 0)
48             shortdoc = doc.substring(0,idx);
49         else
50             shortdoc = doc;
51     }
52     return shortdoc;
56 /**
57  * string_format takes a format-string containing %X style format codes,
58  * and an object mapping the code-letters to replacement text.  It
59  * returns a string with the formatting codes replaced by the replacement
60  * text.
61  */
62 function string_format (spec, substitutions) {
63     return spec.replace(/%(.)/g, function (a, b) substitutions[b]);
67 /**
68  * html_escape replaces characters which are special in html with character
69  * entities, safe for inserting as text into an html document.
70  */
71 function html_escape (str) {
72     return str.replace(/&/g, '&')
73         .replace(/</g, '&lt;')
74         .replace(/>/g, '&gt;')
75         .replace(/"/g, '&quot;');