On Javascript string operations (a tutorial)

There are a lot of things you can do to a String, and usually about fifty different ways to achieve your goal (without even going into RegEx). In order to keep this tutorial/quick reference to a readable length, I’ll only be commenting on a few of the most useful ones, and ignoring RegEx completely. Here are the Javascript string functions we’ll be taking a look at, listed in no particular order.

  • String.indexOf() and String.lastIndexOf()
  • String.split();
  • String.charAt();
  • String.substr();

Using only these four functions, you can achieve greatness! Or at least do what needs to get done without using RegEx, which usually has pretty much the same amount of personal satisfaction.

Using Javascript’s String.indexOf()

String.indexOf(target, start);

You can find the index of any character or string in another string using the indexOf() function, which takes two parameters; target and start. If the requested string or character is not found, this function will return -1. This is especially useful when used in conjunction with one of the other String functions I mentioned above, as you’ll see.

Example:

var myVariable = "Hello, world!";
alert(myVariable.indexOf(","));

>> 5

Using lastIndexOf()

String.lastIndexOf(target, start);

String.lastIndexOf behaves much the same as indexOf(), except that it returns the last found index of a target rather than the first.

Using indexOf() check to if string contains a substring

You can also use indexOf to check if one string is present in another; for example if ‘foo’ can be found in ‘foobar’. This is because indexOf() return a positive integer if the substring can be found, and -1 if it can’t be found. We can use this feature to our advantage like this:

var myString = "foobar";
if(myString.indexOf("foo") > -1) {
    alert("Found string!");
}

>> "Found string!";

Using String.split()

String.split(separator, limit);

String.split() is used to split a string at all occasions of the separator you specify, and takes two parameters, separator and limit. Separator is the character or string you want to split the target string at, and limit is the maximum amount of times you want to split the string. Note: String.split() returns an array, even if it only has one item. In that case, you can access it with String.split()[0], which takes the first element out of the returned array.It’s often used in conjunction with String.indexOf() to do things like split the string at a certain character or string if the index of that character or string is unknown. If you call split with an empty separator (or delimiter, as it’s sometimes called), it will return an array containing each character in your string. If you’re doing that on purpose, chances are that you need String.charAt()– see below. It’s also worth noting that the delimiter is removed from the returned array.

Let’s say you have a list of number, and you want to put them into an array. Here’s how to do it with String.split():

var myNumbers = "1 2 3 4 5 6 7 8 9 10";
console.log(myNumbers.split(" "));

>> ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

Using String.charAt()

String.charAt(index);

charAt() takes a single parameter– index, and will return the character at that index in a string. It’s useful in cases where you need to check if a character is at a particular position or when you want to loop through a string. Be aware that if the specified index doesn’t have a character it will fail silently, returning a falsy value (an empty character, equal to 0, “”, or false, but not equal to undefined or null).

Looping through a string’s characters using charAt():

var myString = "Hello, world!";
for(var i = 0; i<myString.length;i++) {
    console.log(myString.charAt(i));
}
>> H e l l o , w o r l d !

Using charAt() to check the last character in a string:

var myString = "Hello, world!";
if(myString.charAt(myString.length-1) == "!") {
    alert("Last character found!");
} 
>> "Last character found!"

Using String.substr()

String.substr(start, length);

The substr() function takes two parameters, start, which is the zero-based index of the character we want to start our substring at, and length, the length of our substr (who’d have guessed it?). It returns a string composed of the characters from start to start+length of the string you call it on.

Here’s how it works:

var myString = "Hello, world!";
alert(myString.substr(0, 5));
>> "Hello"

In this case, we started our substring at 0 and ended it five characters later. Its value is “Hello”, as you can see.

An interesting thing to note is that passing a negative value into start will result in a substr from the end of the string, like this:

var myString = "Hello, world!";
alert(myString.substr(-6, 5)); 
>> "world"

As you can see, we started our string at six characters from the end of the string (the ‘w’ in ‘world’), and ended it five characters later, at the end of ‘world’.

Putting it all together:

Together, these four functions can be used in many different ways. You can use them for password or URL validation, HTML generation, random word generators, and much more! Here’s an example of a random word generator which demonstrates the uses of these functions:

// here I just copied a list of nouns off the web.

// 'words' is an array of words because I created a string, then split
// it, like this: "my words".split(" "), which splits that string on the 
// spaces.
words = "advice anger answer apple arithmetic badge basket basketball battle beast beetle beggar brain branch bubble bucket cactus cannon cattle celery cellar cloth coach coast crate cream daughter donkey drug earthquake feast fifth finger flock frame furniture geese ghost giraffe governor honey hope hydrant icicle income island jeans judge lace lamp lettuce marble month north ocean patch plane playground poison riddle rifle scale seashore sheet sidewalk skate slave sleet smoke stage station thrill throat throne title toothbrush turkey underwear vacation vegetable visitor voyage year".split(" ");

// syllables will be an array of three letter chunks generated by splitting
// up the words in our previous array. Note that I used the shorthand form
// of creating an array (also called an array literal).
var syllables = [];

for(var i = 0; i<words.length; i++) {
    // loop through the current word's characters with a for loop and charAt()
    var curSyllable = "";
    for(var j = 0; j<words[i].length; j++) {
        curSyllable += words[i].charAt(j);

        // if j is divisible by three, we have a syllable, add it to our list
        if(j % 3 == 0) {
            syllables.push(curSyllable);
            curSyllable = "";
        }
    }
}

// here's where we sort the syllables alphabetically and get rid of any duplicate
// syllables.
var sortedSyllables = syllables.sort();

var results = [];
for (var i = 0; i < syllables.length - 1; i++) {
    if (sortedSyllables[i + 1] != sortedSyllables[i]) {
        results.push(sortedSyllables[i]);
    }
}

syllables = results;
var word = "";

// finally, generate a word from the syllables.
for(var i = 0, numSyllables = Math.floor(Math.random()*4) + 2; i < numSyllables; i++) {
    word += syllables[Math.floor(Math.random()*syllables.length)];
}

alert(word);

Try the code in a working environment here.

Wrapping up

If you have any questions or corrections about this article or would like to see more demonstrations, be sure to let me know via comment. I’ll be doing another article on RegEx later, so keep an eye out for that, too!

One thought on “On Javascript string operations (a tutorial)”

  1. THANK YOU SO MUCH FOR THIS.I’ve been going through coderbye and this is the explanation/ use cases I always needed for these methods but could never find ! 😀

Leave a Reply

Your email address will not be published. Required fields are marked *