Javascript 101: A Guide to String Methods in Javascript

This post will explore how you can use string methods in Javascript to solve your everyday web development problems and write better code.

If you are just getting started with learning Javascript, you might want to get a quick overview of strings as a data type and how they work in Javascript.

I don't want to get into too much details about the textbook definition of a method at this point. For now, all you have to know is that each data type in Javascript has some more or less unique methods, that you can use to modify data. You will use these methods a lot. So it's worth spending some time working with them.

string.split( )

This method splits a string up into an array. You can pass any kind of string as separator to the method.

var string = "red,blue,green,white"
// returns ["red","blue","green","white]

var string = "I eat pasta every day";
string.split(" ");
//returns ["I","eat","pasta","every","day"]

var string = "helloaoldafriend";
//returns ["hello","old","friend"]

var string = "more cowbell";
//returns ["m","o","r","e"," ","c","o","w","b","e","l","l"]

You can really use any kind of string as separator here. Be aware, that your separator will be removed from your string (letter "a" in the third example). If your string is empty, .split("") will separate the string by characters, like in the last example. We can also use regular expressions to split our string. (If you just heard the word regular expression for the first time, you should have a look at RegexOne.)

var string = "";
//returns ["www", "mywebsite", "com", "pageTitle", "searchterm", "test"]

var string = "RedBlueYellowGreen";
//returns ["", "ed", "lue", "ellow", "reen"]
//doesn't quite look like it should. Remember, the separator is removed
//we need positive lookahead here
//returns ["Red","Blue","Yellow","Green"]

string.split() will come in handy whenever you need to clean up a string and structure it for further use. This is especially the case for urls, user input, file names (and their endings myFile.jpg, myDoc.pdf etc.). As strings don't naturally come with a .reverse() method, splitting them into an array, reversing them and joining them back together is a common way to tackle that challenge. Reversing a string is a pretty common interview question for junior positions by the way. It's also important to know that splitting a string won't cause your original variable to change.

var string = "I eat pasta every day"
console.log(string) // logs "I eat pasta every day"
var arr = string.split(" "); 
console.log(splitted) // logs ["I","eat","pasta","every","day"]

In this last example we now have two variables. string still remaining our original string and arr, an array which holds the separated elements of our string.

string.indexOf( ) and string.lastIndexOf( )

Both of these methods enable you to search a string for specific characters. indexOf() will look for the first occurence in the string, while lastIndexOf(), will (you might have guessed it) look for the last occurence of the character.

var string = "elephant"
string.indexOf("e"); // returns 0
string.indexOf("a"); // returns 5
string.lastIndexOf("e"); // returns 2
string.indexOf("u"); // returns -1

The last example is interesting, as it shows us a value of -1 for a character which doesn't exist within the string. This behaviour is quite useful, as it allows us to check for non-existent characters in our string. While there isn't much special to say about these methods, they will show their true strength if you use them in combination with other methods.

string.slice( )

string.slice() let's you literally slice off a part of your string. You can pass two numbers to this methods and define where the slice should begin and where it should end.

var string = "fireworks";
//returns "fire"

var string = "Mr. Jones";
//returns "Jones"

Just like in the example of string.split(), we are not modifying our original data. If we want to keep using the sliced part of the string, we need to assign it to a new variable.

var string =  "Learn Javascript";
var sliced = string.slice(0,10);
console.log(string) // logs "Learn Javascript"
console.log(sliced) // logs "Learn Java"

What if we only want to remove the beginning of the word? Strings have a useful property called string.length, which will return a number with the length of our string

var string =  "Learn Javascript";
console.log(string.length) // logs 16
string.slice(6,string.length) //returns "Javascript"

You can also use a negative index to start counting from the back of the string.

var string = "where is the last word?";
//returns "where is the last"
//returns "is the last"

Finally, if we are not sure where we actually want to slice our string, the previously discussed methods indexOf() and lastIndexOf() are here to save the day.

var string = "Big Bad Text"
string.slice(string.indexOf(" ")+1, string.length);
// returns "Bad Text"
string.slice(0,string.indexOf(" "));
// returns "Big"
string.slice(string.lastIndexOf(" ")+1,string.length);
// returns "Text"
string.slice(string.indexOf(" ")+1,string.lastIndexOf(" "));
// returns "Bad"

You can modify the numbers using mathematical operators too. I've done that in the case above, to avoid having whitespaces in my slices. A final example shows how we could use string.slice() to look for the last item in an enumeration and replace the last "," with and.

var string = "coffee, cookies, cake";
var slicedLeft = string.slice(0,string.lastIndexOf(","));
var slicedRight = string.slice(string.lastIndexOf(",")+2,string.length);
console.log(slicedLeft); // logs "coffee, cookies"
console.log(slicedRight); // logs "cake"
var result = slicedLeft + " and " +slicedRight +".";
console.log(result); // logs "coffee, cookies and cake."

Are you still looking for a reason why you'd ever want to slice strings? Just think about blog posts. Maybe on the frontpage you only want to show an excerpt of 50 characters. String.splice() to the rescue! Another case might be limiting user input. Or you might want to modify strings like we just did in the last example.

string.replace( )

This method enables you to easily replace certain characters in your string.

var string = "I like tea";
var replaced = string.replace("tea","coffee");
console.log(string); // logs "I like tea"
console.log(replaced); // logs "I like coffee"

var string = "Welcome to our website, #username#";
var user = "Peter";
var replaced = string.replace("#username#",user);
// logs "Welcome to our website, Peter"

Once again, our original string remains untouched. The string.replace method also works very well in combination with Regular Expressions.

var string = "m.y(te+xt"
var replaced = string.replace(/[^\w\d\s]/g,"");
// logs "mytext"

var string = "RedGreenBlue"
var replaced = string.replace(/(.)([A-Z])/g,"$1 $2");
//logs "Red Green Blue"

In the first example I've given an empty string "" to the replace method, resulting in characters being removed instead of replaced.

string.toUpperCase( ) and string.toLowerCase( )

Finally, we shouldn't miss the chance to speak about these two useful methods. The principle behind them is pretty simple and you might have already guessed what they do.

var string = "Hello there, I'm a string"
var uppercased = string.toUpperCase();

var string "hEllO tHeRE I'M A strING"
var lowercased = string.toLowerCase();
//logs "hello there, i'm a string"

While this isn't really spectacular, it can help you in situations where you want to compare user input to your datasets. Think about commands. Entering /info might give the user details about your app. The user might enter '/Info' with a capital letter and your app ends up not recognizing this command.

There quite a few other methods for strings in Javascript but these are the ones I use most. If you are curious in reading more about this, there are quite a few resources for further reading.