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" string.split(","); // returns ["red","blue","green","white] var string = "I eat pasta every day"; string.split(" "); //returns ["I","eat","pasta","every","day"] var string = "helloaoldafriend"; string.split("a"); //returns ["hello","old","friend"] var string = "more cowbell"; string.split(""); //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 = "www.mywebsite.com/pageTitle?searchterm=test"; string.split(/[^\w\d\s]/); //returns ["www", "mywebsite", "com", "pageTitle", "searchterm", "test"] var string = "RedBlueYellowGreen"; string.split(/[A-Z]/); //returns ["", "ed", "lue", "ellow", "reen"] //doesn't quite look like it should. Remember, the separator is removed //we need positive lookahead here string.split(/(?=[A-Z])/); //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
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" string.split(","); 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() 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"; string.slice(0,4); //returns "fire" var string = "Mr. Jones"; string.slice(4,9); //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.
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
You 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) //returns "where is the last" string.slice(6,-6) //returns "is the last"
Finally, if we are not sure where we actually want to slice our string, the previously discussed methods
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
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.
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); console.log(replaced); // 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,""); console.log(replaced) // logs "mytext" var string = "RedGreenBlue" var replaced = string.replace(/(.)([A-Z])/g,"$1 $2"); console.log(replaced) //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(); console.log(uppercased); // logs "HELLO THERE, I'M A STRING" var string "hEllO tHeRE I'M A strING" var lowercased = string.toLowerCase(); console.log(lowercased); //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.