1. Strings

Introduction

#-----------------------------
string = '\\n'                       # two characters, \ and an n
string = "\\n"                       # two characters, \ and an n
string = 'Jon \'Maddog\' Orwant'     # literal single quotes
string = "Jon 'Maddog' Orwant"       # literal single quotes
#-----------------------------
string = "\n"                        # a "newline" character
string = '\n'                        # a "newline" character
string = "Jon \"Maddog\" Orwant"     # literal double quotes
string = 'Jon "Maddog" Orwant'       # literal double quotes
#-----------------------------

Accessing Substrings

value = string.substring offset, count
value = string.substring offset

#-----------------------------
string = "This is what you have"

first  = string.substring 0, 1                  # "T"
start  = string.substring 5, 2                  # "is"
rest   = string.substring 13                    # "you have"
last   = string.substring string.length - 1     # "e"
end    = string.substring string.length - 4     # "have"
piece  = string.substring string.length - 8, 16 # "you"
#-----------------------------
# you can test substrings with match()
if string.substring(10).match /pattern/
    console.log "Pattern matches in last 10 characters\n"

#-----------------------------
cut2fmt = (positions) ->
    template   = ''
    lastpos    = 1
    for place in positions
        template += "A" + (place - lastpos) + " "
        lastpos   = place
    template += "A*"

fmt = cut2fmt([8, 14, 20, 26, 30])
console.log fmt
# A7 A6 A6 A6 A4 A*
#-----------------------------

Establishing a Default Value

Exchanging Values Without Using Temporary Variables

Converting Between ASCII Characters and Values

Processing a String One Character at a Time

Reversing a String by Word or Character

Expanding and Compressing Tabs

Expanding Variables in User Input

Controlling Case

Interpolating Functions and Expressions Within Strings

Indenting Here Documents

Reformatting Paragraphs

Escaping Characters

Trimming Blanks from the Ends of a String

Parsing Comma-Separated Data

Soundex Matching

Program: fixstyle

Program: psgrep