|

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.

    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.

    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.

    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.

    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.

    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.

    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.

    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.

    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.

    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()

    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.

    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.


    4. String.prototype.trim()

    string.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

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


    5. String.prototype.charAt()

    string.charAt(index)

    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


    6. String.prototype.charCodeAt()

    string.charCodeAt(index)

    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().

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


    7. String.prototype.toUpperCase()

    string.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


    8. String.prototype.match()

    string.match(regexp)

    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


    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.


    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


    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


    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.


    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

    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()

    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


    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

    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


    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!

    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.