JavaScripTools Manual

JavaScriptUtil

Working with strings

There are several functions to perform operations on strings.

The best place to look at the JavaScriptUtil API documentation, that have a complete list of functions. Here, the idea is not to replicate that information, but to give a basic understanding.


The trim, ltrim, rtrim, crop, lcrop and rcrop functions remove unwanted characters from the string. trim, ltrim and rtring removes whitespaces, while crop removes a number of characters from the string.

Examples:
trim(" HELLO ") -> "HELLO"
ltrim("\nHELLO\n") -> "HELLO\n"
rtrim(" HELLO ") -> " HELLO"
crop("ABCDEFGH", 4, 2) -> "ABCDGH"
lcrop("ABCDEFGH", 3) -> "DEFGH"
rcrop("ABCDEFGH", 3) -> "ABCDE"

The lpad and rpad functions returns a string with, at least, the specified length, completing it on the left or right with a specified character (a space by default).

Examples:
lpad("a", 5) -> "    a"
lpad("10", "6", "0") -> "000010"
lpad("ABCDE", "3", "/") -> "ABCDE" //The size is not reduced
rpad("A", 3, "*") -> "A**"
rpad("", 5, "-") -> "-----"
rpad("12345", "2", " ") -> "12345" //The size is not reduced

The replaceAll, insertString and capitalize functions calculate "changes" the string (strings are immutable - cannot be changed), returning the new string.

Examples:
replaceAll("I am NAME", "NAME", "John") -> "I am John"
insertString("IJohn", 1, " am ") -> "I am John"
capitalize("i am john") -> "I Am John"

The onlySpecified, onlyLetters, onlyNumbers and onlyAlpha functions test if a given string contains only certain characters.

Examples:
onlySpecified("123213321", "123") -> true
onlySpecified("123213321", "0123") -> false
onlyLetters("Testing") -> true
onlyLetters("Just testing") -> false (there's a space)
onlyAlpha("abc123") -> true

The left, right and mid functions select a part of a given string, returning the substring. Those functions use the standard substring method, and are just other ways of using that method, because they care about number of characters, not indexes (except the mid second parameter, because it is an index).

Examples:
left("Home sweet home", 4) -> "Home"
right("Home sweet home", 4) -> "home"
mid("Home sweet home", 5, 3) -> "swe"

The escapeCharacters and unescapeCharacters functions escape / unescape a string, so it can be written inside a dynamic JavaScript block inside a string, without messing the code.

Examples:
var str = "line1\nline2";
eval("alert('" + str + "')") -> ERROR!!!
eval("alert('" + escapeCharacters(str) + "')") -> OK
unescapeCharacters("abc\\ndef") -> "abc\ndef"




Previous:
The declared constants
Table of Contents Next:
Working with objects