String Functions

The standard library’s strings package provides many useful string-related functions. Here are some examples to give you a sense of the package.

We alias fmt.Println to a shorter name as we’ll use it a lot below.

Here’s a sample of the functions available in strings. Since these are functions from the package, not methods on the string object itself, we need to pass the string in question as the first argument to the function. You can find more functions in the strings package docs.

// Requires Node.js environment

const s = require('string');
const p = console.log;

p("Contains:  ", s("test").contains("es"));
p("Count:     ", s("test").count("t"));
p("HasPrefix: ", s("test").startsWith("te"));
p("HasSuffix: ", s("test").endsWith("st"));
p("Index:     ", s("test").indexOf("e"));
p("Join:      ", ["a", "b"].join("-"));
p("Repeat:    ", s("a").repeat(5));
p("Replace:   ", s("foo").replaceAll("o", "0"));
p("Split:     ", s("a-b-c-d-e").split("-"));
p("ToLower:   ", s("TEST").toLowerCase());
p("ToUpper:   ", s("test").toUpperCase());

To run the program, save the code in a file and run it using Node.js.

$ node string-functions.js
Contains:   true
Count:      2
HasPrefix:  true
HasSuffix:  true
Index:      1
Join:       a-b
Repeat:     aaaaa
Replace:    f00
Replace:    f0o
Split:      [ 'a', 'b', 'c', 'd', 'e' ]
ToLower:    test
ToUpper:    TEST

Now that we can run and understand basic string operations, let’s learn more about the language.