In this post we are going to explore how we can use string methods in order to solve both simple and complex problems in everyday development. If you just started learning JavaScript, you might find a quick recap of strings as a data type. You will use these methods a lot. So it’s worth spending some time working with them.

String.split()

This method splits a String into an array of strings. The syntax of the method is like:

str.split([separator[, limit]]);

The separator parameter is an optional parameter, that specifies the character(s) to use for separating the string. If the separator is an empty string, str is converted to an array of characters. If the separator does not exist in the string, the method will return an array with one element consisting of the entire string.

The limit parameter is another optional parameter. This parameter is an integer specifying a limit on the number of splits to be found. This means that the split() method will split on every match of the separator, until the limit of split items is reached, or there are no separator instances left.

var string = "red,blue,green,white,gunmetal";
string.split(","); // returns ["red","blue","green","white","gunmetal"]

string = "Heresy grows from idleness";
string.split(" "); // returns ["Heresy","grows","from","idleness"]

string = "Helloadarknessamyaoldafriend";
string.split("a", 3); // returns ["Hello", "d", "rkness"]

string = "In our Hearts";
string.split(""); // returns ["I", "n", " ", "o", "u", "r", " ", "H", "e", "a", "r", "t", "s"]

As you can see you can use any string as a separator here. But note that our separator will be removed from the string (the letter “a” from the third example). If the 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 (you can check these regular expressions in a site like Regex101).

var string = "www.mywebsite.com/pageTitle?searchTerm=test";
string.split(/[^\w\d\s]/); 
//returns ["www", "mywebsite", "com", "pageTitle", "searchTerm", "test"]

string = "CoolGuysDontLookAtExplosions"
string.split(/(?=[A-Z])/);
// returns ["Cool", "Guys", "Dont", "Look", "At", "Explosions"]

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.mundo, myLectitioDivinitatus.pdf etc.). Reversing a string is a pretty common interview question for junior positions by the way. And can be achieved using split()

var string = "qwerty";
var reversed = string.split("").reverse().join("");
console.log(reversed); // logs ytrewq

Now the above snippet can look a little intimidating if you are a beginner, so bear with me a little, because we are going to break down the code.
string.split("") splits the string to an array of characters, i.e ["q", "w", "e", "r", "t", "y"].
reverse() function will reverse all elements in the array, i.e ["y", "t", "r", "e", "w", "q"].
Finally, join("") function will join the elements of the array in a string, i.e.ytrewq.

Lastly, note that the split() method will not alter your variable, since it returns a new array.

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

String.indexOf() and String.lastIndexOf()

Both of these methods allows us to search a string for specific characters or substrings.
The indexOf method’s syntax is like:

 str.indexOf(searchValue,[fromIndex])

The searchValue is a string representing what we are searching for.
The fromIndex is an optional integer representing the index at which to start the search. The default value is 0. Note that the startValue is a little cranky. If the fromIndex is less than, or equal to 0, the entire string is searched. If the startValue is greater than the size of the string, the string is not searched at all and the method returns -1.

The lastIndexOf method, you guessed it, searches for the last occurrence of the character.
The lastIndexOf method’s syntax is similar to indexOf:

str.lastIndexOf(searchValue[,fromIndex])

The searchValue is a string representing what we are searching for.
The fromIndex is an optional integer representing the index at which to start the search. The default value is +Infinity. Like in indexOf, startValue is a little cranky. If the fromIndex is greater than, or equal to the length of the string, the entire string is searched. If the startValue is less than, or equal to 0, only the first element is checked.

var string = "giraffe";
string.indexOf("g"); // returns 0
string.indexOf("a"); // returns 4
string.lastIndexOf("f") // returns 5
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.

String.slice()

string.slice() allows you to literally slice off a part of a string.
The syntax of the method is like:

str.slice(beginIndex[, endIndex]);

The beginIndex is a zero-based index at which to begin extraction. If the index is negative, it is treaded as strLenght + beginIndex where strLength is the length of the string. If beginIndexis greater than or equal to the length of the string, slice() returns an empty string.

TheendIndex is an optional index before which to end extraction. The character at this index will not be included. If you don’t set an endIndex, slice() extracts to the end of the string.

var string = "fireworks"
string.slice(0,4); // returns "fire"

string = "Constantin Valdor"
string.slice(11); // returns "Valdor"

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 str1 = "The morning is upon us!"
var str2 = str1.slice(12);

console.log(str1); // logs The morning is upon us!
console.log(str2); // logs is upon us!

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 =  "Let's Learn JavaScript";  
console.log(string.length) // logs 22
string.slice(12,string.length) //returns "JavaScript"

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

var string = "Where is the last word?";
string.slice(0,-6); // logs "Where is the last";
string.slice(-5, -1) // logs "word";

Finally, if we are not sure where we actually want to slice our string, indexOf() and lastIndexOf() methods come to play.

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"

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 = "chocolate, cookies, cake";
var right = string.slice(string.lastIndexOf(",") +2);
var left = string.slice(0, string.lastIndexOf(","));

console.log(left); // logs chocolate, cookies
console.log(right); // logs cake

var newString = left+" and "+right;
console.log(newString); // logs chocolate, cookies and cake

String.replace()

This method enables you to easily replace certain characters in your string.
The replace() method’s syntax is like:

str.replace(regexp|substr, newSubstr|function);

The function can take quite a few parameters:
The regexp(pattern) is a regular expression. The match or matches are replaced with newSubStr or the value returned by the specified function. In other words, you can provide a regular expression and replace whatever it matches with either a new substring than is provided, or the output of a provided function.

The substr(pattern) is a String that is to be replaced by newSubStr. Note that it is treated as a regular string, and not as a regular expression. Also note that only the first occurrence of the string will be replaced.

The newSubStr (replacement) is the String that replaces the substring specified by the specified regexp or substr parameter.

Finally the function (replacement) is a function to be invoked in order to create the new substring to be used to replace the matches to the given regexp or substr.

var string = "Welcome to my blog #username#";
var username = "Gregor Eisenhorn";

var replaced = string.replace("#username#",username);
console.log(replaced); // logs "Welcome to my blog Gregor Eisenhorn"

Once again, our original string remains untouched.

var str = "Twas the night before Xmas...";
var newstr = str.replace(/xmas/i, "Christmas");
console.log(newstr); // logs Twas the night before Christmas...

Specifying a string as a parameter

The replacement string can include the following special replacement patterns

Pattern Inserts
$$ Inserts a “$”. This pattern is useful to output currency.
$& Inserts the matched substring. It’s useful for concatenating a particular match.
$` Inserts the portion of the string that precedes the matched substring.
$’ Inserts the portion of the string that follows the matched substring.
$n Where n is a positive integer less than 100, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object.
var str1 = "Oranges 1.90 dollars";
console.log(str1.replace(" dollars","$$")); // logs "Oranges 1.90$"

var str2 = "John Doe";
console.log(str2.replace(/(John)/, "Name: $&")); // logs "Name: John Doe"
console.log(str2.replace(/(Doe)/, '$`')); // logs "John John"
console.log(str2.replace(/(John)/, "$'")); // logs "Doe Doe"

var regex = /(\w+)\s(\w+)/;
var name = "Constantin Valdor";

console.log(name.replace(regex, "$2 $1")); // logs "Valdor Constantin"

Specifying a function as a parameter

You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function’s result (return value) will be used as the replacement string. Also note that the special parameters we talked about above, does not apply.

Possible name Inserts
match The matched substring. (Corresponds to $& above).
p1, p2, … The nth parenthesized submatch string, provided the first argument to replace() was a RegExp object. (Corresponds to $1, $2, etc. above.) For example, if /(\a+)(\b+)/, was given, p1 is the match for \a+, and p2 for \b+.
offset The offset of the matched substring within the whole string being examined. (For example, if the whole string was ‘abcd’, and the matched substring was ‘bc’, then this argument will be 1.)
string The whole string being examined.

The next example replaces fractions with their decimal equivalents.

var str = 'Add 1/4 cup of sugar and 1/2 cup of blueberries.'
str.replace(/(\d+)\/(\d+)/g, function(match, submatch1, submatch2) {
    var num1 = parseInt(submatch1);
    var num2 = parseInt(submatch2);
    return (num1 / num2).toString();
}); // returns "Add 0.25 cup of sugar and 0.5 cup of blueberries."

\d+ means “one or more digits in a row”. We do this twice, both times wrapped in parenthesis, so we can catch the numerator and denominator. In the middle is \/, which is simply an escaped slash /. Put it all together and we’ve got a fraction finder.

This time, instead of a string for the second parameter of replace(), we’re providing a function. This function is called every time a match is found and its return value is what replaces the match. The function takes a couple of parameters, though we’re only using 3 in this example.

The code within the function does the actual fraction/decimal conversion. It takes the first submatch (numerator) and second submatch (denominator), converts them both to integers, divides them to get the decimal value, then returns that as a string.

String.toUpperCase() and String.toLowerCase()

Finally let’s talk about these two useful functions. As you might imagine, these two functions convert a string to upper or lower case respectively. Nothing spectacular going on here.

console.log('alphabet'.toUpperCase()); // logs ALPHABET
console.log('ALPHABET'.toLowerCase()); // logs alphabet
Advertisements