The Top 15 Most Popular JavaScript String Functions

javascript string functions

JavaScript String Functions are the topic of this adventure into programming JavaScript. There are relatively few functions that you need to be aware of, however it is helpful to have a good in depth knowledge of how each string function works in order to get the most out of working with strings in JavaScript. Just like our tutorial covering useful arrays in JavaScript, this tutorial makes use of the same approach. We try to decipher which JavaScript string functions are being used very frequently in the open source ecosystem of frameworks and libraries. Those that are used frequently are deemed more useful and appear at the top of the list in this tutorial.

  • 1What are Strings in JavaScript?
  • 2String.prototype.replace()
  • 3String.prototype.toLowerCase()
  • 4String.prototype.trim()
  • 5String.prototype.charAt()
  • 6String.prototype.charCodeAt()
  • 7String.prototype.toUpperCase()
  • 8String.prototype.match()
  • 9String.prototype.concat()
  • 10String.prototype.substr()
  • 11String.prototype.split()
  • 12String.prototype.fromCharCode()
  • 13String.prototype.substring()
  • 14String.prototype.valueOf()
  • 15String.prototype.slice()
  • 16String.prototype.indexOf()
  • 17Putting It All Together

  • 1. What Are JavaScript Strings?

    Just like most other programming languages, we have a means to represent text by way of strings. The basic description is just that, strings are text. The more technical description of strings would be to refer to them as an ordered collection of unicode characters that is immutable. Immutable simply means you can not change it. Every string has a length, and it corresponds to the number of 16 bit characters it contains. Just like Arrays in JavaScript, Strings make use of zero based indexing. Again, this means the first character in a string actually begins at zero. Every string has a length property that you can very easily query to find out the exact length of any given string. An empty string has a length of zero. Strings are denoted in JavaScript using string literals. All this means is that you type some text and enclose it within either single or double quotes. You can use either convention, but for your own sanity, choose one and stick with it if possible. Here are a few examples of string literals.

    "" // An empty string
    'google is for searching'
    "Don't even think about it!"
    "This is a string\nthat has two lines"
    "twitter is for tweeting"

    Note that if a string is delimited with double quotes, you can use single quotes inside of the string. The reverse is true if you are delimiting with single quotes. In that scenario, you can contain double quotes inside of the string. Of course, you can also use the escape character \ if you need to bend these rules just a bit.

    2. String.prototype.replace()

    string.replace(regexp|substr, newSubStr|function[, flags])

    string.replace() description

    When you want to do a search and replace on a string in JavaScript, the replace() function is the one you want to make use of. This function searches the provided haystack, or string, for one or several substrings that match a given pattern or regular expression. It then replaces those matches with a replacement. You can specify the global g flag to replace all matches if you like when using a regular expression rather than a simple string. If global is not specified, only the first match will be replaced. Check out our tutorial covering regular expressions if you need a refresher on how to use them. They are a beast! In terms of how powerful they are though, they simply can’t be beat.

    Here is where it gets a little dicey, in true JavaScript form. The replacement can not only be a string like you might expect, it can also be a function.

    What replace() returns

    The replace() function returns a new string with matches of the string or regular expression replaced by any replacements made. The string it is called on does not change, only the return value is modified.

    string.replace() function examples

    This example of the replace() function looks at the old string, and replaces instances of javascript with JavaScript. We include both the g and i flags in this example. g indicates that this is a global search and replace, meaning all instances will be replaced. If we had omitted the g flag, only the first instance would be replaced. The i flag is for ignoring the case.

    var oldstring = 'Programming with string in javascript is fun! ' +
        'Old javascript string, not the same as new javascript string';
    var newstring = oldstring.replace(/javascript/gi, 'JavaScript');
    // Programming with string in javascript is fun! Old javascript string, not the same as new javascript string
    // Programming with string in JavaScript is fun! Old JavaScript string, not the same as new JavaScript string

    Here we will use replace() to find instances of the characters AAPL in a string of text, and replace them with the text of Apple. Note that this example works because we include the i flag modifier which indicates that this is case insensitive.

    var oldstring = 'AAPL is a great company with awesome products';
    var newstring = oldstring.replace(/aapl/i, 'Apple');
    //  Apple is a great company with awesome products

    When you have portions of your regular expression surrounded by parenthesis, you can can access that substring match using the $n operator. Let’s see how we do this. In this following example, we have a regular expression which matches four lowercase letters followed by a space, four times in a row. Each collection of four characters is surrounded by parenthesis, so we now have access to the first, second, third, and fourth matches. In the second example we only use the $4 and $3 instances in mixed order to show how the matches are replaced according to position.

    var regularexp = /([a-z]{4})\s([a-z]{4})\s([a-z]{4})\s([a-z]{4})\s/;
    var oldstring = 'aapl goog msft amzn ';
    var newstring = oldstring.replace(regularexp, '$4, $3, $2, $1');
    //  amzn, msft, goog, aapl
    var regularexp = /([a-z]{4})\s([a-z]{4})\s([a-z]{4})\s([a-z]{4})\s/;
    var oldstring = 'aapl goog msft amzn ';
    var newstring = oldstring.replace(regularexp, '$4, $3, $4, $3');
    //  amzn, msft, amzn, msft

    Special Replacement Patterns

    There are a few special replacement pattern characters you can include in the replacement string. Recall, the second parameter to the replace() function is the replacement string. First we will look at the $& operator. This simply inserts the substring matched by the regular expression pattern provided.

    var pattern = /[aA-zZ]*!/g;
    var oldstring = 'Special characters can be used in the replacement string!  Money!';
    var newstring = oldstring.replace(pattern, '$& $&');
    //  Special characters can be used in the replacement string! string!  Money! Money!

    The next special character replacement is the $$ operator. This is for inserting a literal dollar sign into the replacement string. Let’s replace Money! with $ in the replacement string.

    var pattern = /M[aA-zZ]*!/g;
    var oldstring = 'Special characters can be used in the replacement string!  Money!';
    var newstring = oldstring.replace(pattern, '$$');
    //  Special characters can be used in the replacement string!  $

    You can also access the part of the string that comes before that matched substring. For this we will use the $backtick operator. We will find the match of can and replace it with any text that comes before it.

    var pattern = /can/g;
    var oldstring = 'Special characters can be used in the replacement string!  Money!';
    var newstring = oldstring.replace(pattern, '$`');
    // Special characters Special characters  be used in the replacement string!  Money!

    Now we will make use of $’ which inserts the text that comes after the matched substring. We will find the word into, and replace it with any text that comes after that match.

    var pattern = /into/;
    var oldstring = 'You are turning into a pro with this replace function!';
    var newstring = oldstring.replace(pattern, "$'");
    // You are turning  a pro with this replace function! a pro with this replace function!

    Here is a nice table that covers these characters.

    Pattern Inserts
    $$ Inserts a literal dollar sign in the replacement string.
    $& Inserts the matched substring in the replacement string.
    $` Takes the part of the string that comes before the substring match and inserts it into the replacement string.
    $' Takes the part of the string that comes after the substring match and inserts it into the replacement string.
    $n This operator finds the numerical position of the substring match and inserts that particular match in the replacement string as long as the first argument was a regular expression.

    Passing a function as the second argument to replace()

    As we know, the second argument to replace() is typically the replacement string. You can however pass a function as the second parameter. In this scenario, the matching happens first, and then the function is invoked. Whatever that function returns, ends up being the value used as the replacement string.

    var oldstring = 'AAPL GOOG and MSFT are really big technology companies.';
    var newstring = oldstring.replace(/[A-Z]{4}/g, tickerToName);
    function tickerToName(match){
        if(match === 'AAPL'){
            return 'Apple';
        } else if (match === 'GOOG'){
            return 'Google';
        } else if (match === 'MSFT') {
            return 'Microsoft';
    //  Apple Google and Microsoft are really big technology companies.

    The replace() function appears right at the top of our list of useful JavaScript string functions. In looking at some of the examples above we can see why. This function is incredibly powerful and works with both standard strings, regular expressions, and custom functions. It is very involved, and there is a lot to understand in order to use it effectively, most notably understanding regular expressions.

    3. String.prototype.toLowerCase()


    string.toLowerCase() description

    The toLowerCase() function does exactly what you think it would. It simply returns a new string that has been converted to all lower case from the old string. The original string is not changed.

    string.toLowerCase() function examples

    This is a really simple example.

    var oldstring = 'HEY SHORTY, ITS YOUR BIRTHDAY!';
    var newstring = oldstring.toLowerCase();
    //  hey shorty, its your birthday!

    This example has a little bit of a better use case. Let’s build a sluggify function that takes a string, and turns it into it’s slug form.

    var oldstring = 'The Most Popular JavaScript String Functions';
    var pattern = /\s/g;
    function sluggify(str) {
        return str.replace(pattern, '-').toLowerCase();
    var newstring = sluggify(oldstring);
    //  The Most Popular JavaScript String Functions
    //  the-most-popular-javascript-string-functions

    4. String.prototype.trim()


    string.trim() description

    The trim() function removes any whitespace characters from both the beginning and ending of a particular string.

    string.trim() function examples

    var oldstring = ' \r   \n   the string be with you   \v \f     ';
    var newstring = oldstring.trim();
    //   \r   \n   the string be with you   \v \f     
    // the string be with you 
    var stringone = '     abc     ';
    var stringtwo = '     def     ';
    var newstring = stringone.trim() + stringtwo.trim();
    //  abcdef

    trim() works great for data sanitization and other means of cleaning up data before operating on it.

    5. String.prototype.charAt()


    string.charAt() description

    The charAt() function stands for character at. You can find the exact location of a given character in a string when you use this function. It almost reads like, “Tell me the character at position x”. In order for the charAt() function to do it’s job, you must provide an index parameter between 0 and one less than the length of the string you would like to perform the charAt() function on. If the index provided as a parameter is not between 0 and string.length − 1, this function returns an empty string.

    This kinds of works like indexOf() in reverse. With charAt(), you provide a numerical value, and charAt() tells you the character that lives at that location. With indexOf(), you provide the character, and indexOf() tells you the index location it lives at.

    string.charAt() function examples

    var lightsaber = 'Super Powerful Slicing Ability';
    // S
    console.log(lightsaber.charAt(lightsaber.length - 1));
    // y

    6. String.prototype.charCodeAt()


    string.charCodeAt() description

    The charCodeAt() function works almost like charAt() except instead of returned the character at a specific index position, it returns the encoding of the character at a given position in the string.

    string.charCodeAt() function examples

    Here we will use the alphabet as a string, and learn the Unicode number associated with every letter by making use of charCodeAt().

    var alphabet = 'abcdefghijklmnopqrstuvwxyz';
    console.log(alphabet.charCodeAt(0)); // 97
    console.log(alphabet.charCodeAt(1)); // 98
    console.log(alphabet.charCodeAt(2)); // 99
    console.log(alphabet.charCodeAt(3)); // 100
    console.log(alphabet.charCodeAt(4)); // 101
    console.log(alphabet.charCodeAt(5)); // 102
    console.log(alphabet.charCodeAt(6)); // 103
    console.log(alphabet.charCodeAt(7)); // 104
    console.log(alphabet.charCodeAt(8)); // 105
    console.log(alphabet.charCodeAt(9)); // 106
    console.log(alphabet.charCodeAt(10)); // 107
    console.log(alphabet.charCodeAt(11)); // 108
    console.log(alphabet.charCodeAt(12)); // 109
    console.log(alphabet.charCodeAt(13)); // 110
    console.log(alphabet.charCodeAt(14)); // 111
    console.log(alphabet.charCodeAt(15)); // 112
    console.log(alphabet.charCodeAt(16)); // 113
    console.log(alphabet.charCodeAt(17)); // 114
    console.log(alphabet.charCodeAt(18)); // 115
    console.log(alphabet.charCodeAt(19)); // 116
    console.log(alphabet.charCodeAt(20)); // 117
    console.log(alphabet.charCodeAt(21)); // 118
    console.log(alphabet.charCodeAt(22)); // 119
    console.log(alphabet.charCodeAt(23)); // 120
    console.log(alphabet.charCodeAt(24)); // 121
    console.log(alphabet.charCodeAt(25)); // 122

    The output above is the Unicode number of each letter of the alphabet in lowercase.

    7. String.prototype.toUpperCase()


    string.toUpperCase() description

    Just like you think it might, the toUpperCase() function turns a string into an all uppercase version of itself. Do note that the original string is left untouched, while the returned string is the all uppercase version.

    string.toUpperCase() function examples

    var light = 'lightsabers';
    var sabers = light.toUpperCase();
    // lightsabers

    8. String.prototype.match()


    string.match() description

    The match() function makes use of powerful regular expression patterns. In order for match() to work, you must pass it one parameter, which is a regular expression. match() will then use that pattern to find all matches in the given string, then return an array of any matches. If there are no matches based on the regular expression you pass in, then match() returns null.

    string.match() function examples

    var numbersinstring = '50 plus 50 equals 100!'
    var result = numbersinstring.match(/\d+/g);
    //  ["50", "50", "100"]
    var regExPattern = /(\w+):\/\/([\w.]+)\/(\S*)/;
    var text = "Find great tutorials at";
    var result = text.match(regExPattern);
    var fullurl = result[0];
    var protocol = result[1];
    var host = result[2];
    var path = result[3];
    // http
    // javascript-string-functions/

    9. String.prototype.concat()

    string.concat(string2, string3[, …, stringN])

    string.concat() description

    In JavaScript you can use the concat() function to add strings together. You could also simply use the + operator, which is also very easy. You can pass as many strings as you like to the concat() function. Let’s look at a few examples of string.concat() in action.

    var firstString = 'JavaScript is ';
    var newString = firstString.concat('awesome, ', 'fun, ', 'and useful!');
    //  JavaScript is awesome, fun, and useful!
    var one = 'abcdefg';
    var two = 'hijklmnop';
    var three = 'qrstuv';
    var four = 'wxy and z';
    var five = one.concat(two, three, four);
    //  abcdefghijklmnopqrstuvwxy and z

    10. String.prototype.substr()

    string.substr(start[, length])

    string.substr() description

    The substr() function looks into a string and extracts a specific number of characters from that string based on the provided start and length parameters. The start parameter is where the search for the substring begins, and the length parameter specifies the number of characters to extract beginning from start. If the length parameter is not provided, all characters from the start position are extracted from the original string. If the length is 0 or a negative value, substr() will return an empty string. Finding a string within a string, or substring, is very common in any programming language. In addition to substr(), you can also make use of the related substring() and slice() functions which we cover here as well.

    string.substr() function examples

    var supercali = 'supercalifragilisticexpialidocious';
    console.log(supercali.substr(0, 5));
    //  super
    console.log(supercali.substr(5, 4))
    //  cali
    console.log(supercali.substr(9, 11))
    //  fragilistic
    //  expialidocious
    //  supercalifragilisticexpialidocious
    var stringtut = 'Epic JavaScript String Tutorial';
    var tuts = stringtut.substr(0, 15);
    var plus = stringtut.substr(16, 15);
    //  Epic JavaScript
    //  String Tutorial

    11. String.prototype.split()

    string.split([separator[, limit]])

    string.split() description

    The split() function explodes a string into an array of characters based on a provided separator. You can optionally limit the number of splits to be found by passing an integer value as the second argument to the split() function. This is a very useful function.

    In this example, we have all the JavaScript string functions linked together with the . character as one big string. Using string.split(), we will turn that one string into an array, with each function name occupying a slot in the array.

    string.split() function examples

    var oneBigString = 'fromCharCode.fromCodePoint.anchor.big.blink.bold.charAt.charCodeAt.codePointAt.concat.endsWith.' +
        '' +
        '' +
    var newArray = oneBigString.split('.');
    //  ["fromCharCode", "fromCodePoint", "anchor", "big", "blink", "bold", "charAt", "charCodeAt", "codePointAt", 
    // "concat", "endsWith", "fixed", "fontcolor", "fontsize", "includes", "indexOf", "italics", "lastIndexOf", "link",
    // "localeCompare", "match", "normalize", "quote", "repeat", "replace", "search", "slice", "small", "split", "startsWith",
    // "strike", "sub", "substr", "substring", "sup", "toLocaleLowerCase", "toLocaleUpperCase", "toLowerCase", "toSource", 
    // "toString", "toUpperCase", "trim", "trimLeft", "trimRight", "valueOf", "raw"]

    12. String.prototype.fromCharCode()

    String.fromCharCode(num1[, …[, numN]])

    string.fromCharCode() description

    The fromCharCode() function is used to create a string from Unicode encodings. You pass one or more integers to the fromCharCode() function as parameters that specify the Unicode encodings of the characters in the string to be created.

    string.fromCharCode() function examples

    Here we will pass in a bunch of Unicode numbers to produce a secret message.

    var secretcode = String.fromCharCode(69, 118, 101, 114, 121, 116, 104, 105, 110, 103, 32, 105, 115, 32, 65, 87, 69, 83, 79, 77, 69);
    //  Everything is AWESOME

    13. String.prototype.substring()

    string.substring(indexStart[, indexEnd])

    string.substring() description

    The substring() function has two parameters, those being indexStart and indexEnd. The indexStart parameter is required and specifies the position of where to start the extraction of characters. The indexEnd is optional and specifies the location where the extraction of characters should end. The character that is at the indexEnd position, is not actually included in the extracted substring. If the indexEnd parameter is not provided, then all characters from the start position until the end of the string are extracted. A curious behavior of the substring() function is that if the value of indexStart is greater than the value of indexEnd, substring() will automatically swap these two arguments!

    note: Just like in JavaScript Arrays, JavaScript Strings start at index 0.

    string.substring() function examples

    var supercali = 'supercalifragilisticexpialidocious';
    console.log(supercali.substring(0, 5));
    //  super
    console.log(supercali.substring(5, 9));
    //  cali
    console.log(supercali.substring(9, 20));
    //  fragilistic
    //  expialidocious
    //  supercalifragilisticexpialidocious
    var theForce = 'The force is strong with you because you are AWESOME';
    var last8oftheForce = theForce.substring(theForce.length - 8);
    //  AWESOME

    note: The substr() and substring() functions are almost exactly the same, but there are some subtle differences. First off, the second parameter of substring() tells JavaScript where the extraction of the substring needs to stop. This character is not included in the substring. For the substr() function, that second parameter actually is the number of characters to return beginning from the start position. So with substring(), you need to specify the exact index ending location, while with substr() you must specify the length of the substring to return. If you are not getting the results you expect from one of these functions, this might be one of the reasons why. In addition to this, substr() does not work in Internet Explorer 8 and earlier.

    14. String.prototype.valueOf()


    string.valueOf() description

    The valueOf() function is a method of JavaScript’s build in String object and returns the primitive value of a String object as a string data type. The value returned is the same as you would get from String.prototype.toString().

    string.valueOf() function examples

    var str = new String('Jumping Jack Flash');
    // Jumping Jack Flash 

    15. String.prototype.slice()

    string.slice(beginSlice[, endSlice])

    string.slice() description

    The slice() JavaScript function takes two parameters. beginSlice is the first parameter, and endSlice is the second parameter. You may also see these parameters begin referred to as start and end. beginSlice is a required parameter and specifies the beginning point of the extraction of the substring. The endSlice parameter is optional. It specifies the location at which to stop the extraction. The character specified by endSlice is not included in the extracted substring. If you do not provide the endSlice parameter, all characters beginning from the beginSlice position will be extracted from the original string as part of the substring. We can see that the slice(), substring(), and substr() functions all work in a very similar fashion.

    string.slice() function examples

    var usForce = 'The Force Is With Us!';
    var youforce = usForce.slice(0, 19);
    //  The Force Is With U

    note: The slice() and substring() functions are almost the same. One difference however is that if the start parameter is greater than the stop parameter, the substring() function will swap those two parameters. The slice() function has no such ability to swap those two parameters.

    16. String.prototype.indexOf()

    string.indexOf(searchValue[, fromIndex])

    string.indexOf() description

    The indexOf() function is very useful, especially when working with a substring in JavaScript. This function returns the position of the first occurrence of a given value in a string. If that value is not found in the string, then indexOf() will return -1.

    string.indexOf() function examples

    var email = '';
    var index = email.indexOf('@');

    17. Putting It All Together

    We’ve covered a lot of ground here in this epic collection of the most useful JavaScript String Functions! Let’s now move beyond the simple definitions of the functions, and take a look at how to do something kind of neat with our newfound knowledge. We’ll make a small application that accepts user input in the form of an email address, and allows the user to click a button after entering the email address. When the button is clicked, we will make use of the indexOf() and substring() functions to break apart that email on the @ symbol. We will then put the text that comes before the @ symbol in one field, and the text that comes after the @ symbol in another. Let’s check it out!

    <form class="form-horizontal">
        <div class="form-group">
            <label for="textEmailAddress" class="col-sm-4 control-label">Email</label>
            <div class="col-sm-8">
                <input type="email" class="form-control" id="textEmailAddress" value="">
        <div class="form-group">
            <label for="textEmailPart" class="col-sm-4 control-label">Before @ Symbol</label>
            <div class="col-sm-8">
                <input type="text" class="form-control" id="textEmailPart">
        <div class="form-group">
            <label for="textDomainPart" class="col-sm-4 control-label">After @ Symbol</label>
            <div class="col-sm-8">
                <input type="text" class="form-control" id="textDomainPart">
        <div class="form-group">
            <div class="col-sm-offset-4 col-sm-8">
                <div onclick="breakOnAtSymbol()" class="btn btn-lg btn-success">Break On @ Symbol</div>
        function breakOnAtSymbol() {
            var email = document.getElementById('textEmailAddress').value;
            var emailpart = email.substring(0, email.indexOf('@'));
            var domainpart = email.substring(email.indexOf('@') + 1);
            document.getElementById('textEmailPart').value = emailpart;
            document.getElementById('textDomainPart').value = domainpart;

    Try it!

    Break On @ Symbol

    JavaScript String Functions Summary

    In this episode, we covered all of the bread and butter fundamentals of working with the built in string functions in the JavaScript language. The most popular JavaScript frameworks and libraries make extensive use of these functions to provide the magic that they do. By taking some time to review all of the functions listed here, you’ll be more comfortable in your day to day JavaScript programming.