In this article I want to talk about few basic string methods which are most commonly used in Javascript and very useful when it comes to solve problems and algorithms.
I've been working on solving algorithms both on FreeCodeCamp and CodeWars for the last 4 weeks and find out I used a lot of times this methods.
If you are interested in Arrays Methods you can check my post about them:
Javascript Arrays Methods You Must Know to Become an Algorithms Wizard
1) Getting length of a string with .length
let str = "i am a string";
console.log(str.length); //13
2) Getting an array from a string with .split(). Remember it is possible to use a specified separator string to determine where to make each split.
const str = "Luke, I am your Father";
console.log(str.split());//[ 'Luke, I am your Father' ]
console.log(str.split(''));//["L", "u", "k", "e", ",", " ", "I", " ", "a", "m", " ", "y", "o", "u", "r", " ", "F", "a", "t", "h", "e", "r"]
console.log(str.split(' '));//[ 'Luke,', 'I', 'am', 'your', 'Father' ]
console.log(str.split(','));//[ 'Luke', ' I am your Father' ]
Let's see an easy algorithm I solved on CodeWars where given a string of words the function must return an array of integers equals to the words length.
function wordsLength(str) {
return str.split(' ') //first split the string at spaces to have an array of words;
.map(word => word.length); //second use array map() to trasform any array element to its length with .length;
}
wordsLength('Luke, I am your father'); //[ 5, 1, 2, 4, 6 ]
3) Convert a string into upper case with toUpperCase()
const str = 'I find your lack of faith disturbing.';
console.log(str.toUpperCase()); //I FIND YOUR LACK OF FAITH DISTURBING.
4) Convert a string into lower case with toLowerCase()
const str = 'Help me, Obi-Wan Kenobi. You’re my only hope.';
console.log(str.toLowerCase()); //help me, obi-wan kenobi. you’re my only hope.
5) Check if a string contains specified characters includes(). It will return a boolean value (true or false). It is possible to add the position within the string at which to begin searching
const str = 'The Force will be with you. Always.';
console.log(str.includes('Force')); //true
//Attention: it is case sensitive!
console.log(str.includes('force')); //false
//Often it will be better to transform the given string to lowercased
//and then check if it includes or not what you are looking for.
const newStr = str.toLowerCase();
console.log(newStr.includes('force')); //true
//Add the position where to start searching
console.log(str.includes('w', 0)); //true
console.log(str.includes('T', 1)); //false
6) Check if a string starts with specified characters with startWith(). It will return a boolean value and it is possible to add the position where to start searching. It is case sensitive.
const str = 'Never tell me the odds!';
console.log(str.startsWith('Never')); //true
console.log(str.startsWith('Never', 1)); //false
console.log(str.startsWith('never', 0)); //false
7) Check if a string ends with specified characters with endsWith(). It will return a boolean value and it is possible to add the length parameter (optional). It is case sensitive.
const str = 'Do. Or do not. There is no try.';
console.log(str.endsWith('try.')); //true
console.log(str.endsWith('Try.')); //false
console.log(str.endsWith('try', 30)); //true
console.log(str.endsWith('try.', 30)); //false
7) Check for the first occurrence of a specified value in a string with .indexOf(). If the value is not in the string it will return -1. It is possible to add a second parameter starting the search at specified index.
const str = 'When gone am I, the last of the Jedi will you be. The Force runs strong in your family. Pass on what you have learned.';
console.log(str.indexOf('h')); //1
console.log(str.indexOf('H')); //-1
console.log(str.indexOf('h', 2)); //17
console.log(str.indexOf('J', str.length)); //-1
8) Check for the last occurrence of a specified value in a string with .lastIndexOf(). If the value is not in the string it will return -1. It is possible to add the index of the last character in the string to be considered as the beginning of a match.
const str = 'When gone am I, the last of the Jedi will you be. The Force runs strong in your family. Pass on what you have learned.';
console.log(str.lastIndexOf('h')); //105
console.log(str.lastIndexOf('h', 100)); //97
console.log(str.lastIndexOf('.')); //117
console.log(str.lastIndexOf('.', 0)); //-1
9) Repeat a given string with .repeat().
const str = 'There’s always a bigger fish.';
console.log(str.repeat(2));//There’s always a bigger fish.There’s always a bigger fish.
//Attention: count will be converted to integer!
console.log(str.repeat(5.5));//There’s always a bigger fish.There’s always a bigger fish.There’s always a bigger fish.There’s always a bigger fish.There’s always a bigger fish.
10) Replace a pattern in a given string with replace(). The pattern can be a string or a regex and the replacement can be a string or a function to be called on each match. Attention: if the replacer or pattern is a string only the first occurence will be replaced.
const string = 'Fear is the path to the dark side.';
console.log(string.replace('Fear', 'Tears')); //Tears is the path to the dark side.
console.log(string.replace(/a/gi, 'A'));//FeAr is the pAth to the dArk side.
11) Get a specific character from a string using charAt(). A string representing the character (exactly one UTF-16 code unit) at the specified index is returned. An empty string if index is out of range!
const string = 'Fear leads to anger';
console.log(string.charAt(1));//e
console.log(string.charAt(string.length - 1));//r
console.log(string.charAt(string.length));//'' Index out of range!
//Attention: if no index is provided the default one is 0;
console.log(string.charAt());//F
12) Get the UTF-16 code of the letter at the given index in a string with charCodeAt(). This method is very useful with algorithms like ROT13 or Caesar Cypher. If no index is provided the default one is 0.
const string = 'We must keep our faith in the Republic.';
console.log(string.charCodeAt(0));//87
console.log(string.charCodeAt(5));//115
//If you want all the UTF-16 values of any letter in a string
//split the string to have an array of letters
//map the array and change any letter to its utf-16 value with charCodeAt();
const utfValuesArr = string.split('').map(letter => letter.charCodeAt());
console.log(utfValuesArr);
//[87, 101, 32, 109, 117, 115, 116, 32, 107, 101, 101, 112, 32, 111, 117, 114, 32, 102, 97, 105, 116, 104, 32, 105, 110, 32, 116, 104, 101, 32, 82, 101, 112, 117, 98, 108, 105, 99, 46]
13) Get a string created from the specified sequence of UTF-16 code units with the static String.fromCharCode() method.
console.log(String.fromCharCode(65));//A
console.log(String.fromCharCode(105, 106, 107));//ijk
console.log(String.fromCharCode(32));//'' empty space!
const arr = [77, 97, 121, 32, 116, 104, 101, 32, 70, 111, 114, 99, 101, 32, 66, 101, 32, 87, 105, 116, 104, 32, 89, 111, 117];
const quote = arr.map(n => String.fromCharCode(n));
console.log(quote.join('')); //May the Force Be With You
14) Get a section of a string, returned in a new string, without modifying the original one with slice(). It takes two parameter. BeginIndex, or where to start to slice the string and the optional EndIndex where to stop to slice it. If no EndIndex is provided it will slice the string to the end. Attention: A negative index counts backwards from the end of the string
const string = 'I’m just a simple man trying to make my way in the universe.';
console.log(string.slice(1));//’m just a simple man trying to make my way in the universe.
console.log(string.slice(0,10));//I’m just a
console.log(string.slice(-3));//se.
15) Get the part of the string between the start and end indexes, or to the end of the string with substring(). Attention: any argument value that is less than 0 or greater than stringName.length is treated as if it were 0 and stringName.length respectively. Any argument value that is NaN is treated as if it were 0.
const string = 'Darth Vader';
console.log(string.substring(0));//Darth Vader
console.log(string.substring(6));//Vader
console.log(string.substring(1,6));//arth
16) Remove whitespaces from both ends of a string with trim().
const string = ' Yoda ';
console.log(string.trim());//Yoda
This don't want to be an exhaustive list of all javascript string methods, but a list of the ones I find out to be the most important when it comes to solve problems and algorithms.
To get better at JS and problem solving I suggest to "play" a lot with all these methods and to subscribe both on FreeCodeCamp or Codewars where you can find a lot of algorithms to work with and brush up your javascript knowledge.
On Codewars you can look for 7kyu or 6kyu algorithms about "strings" and train with them. It will be funny!
I will update this article with new information and some algorithms on strings, based on the reactions and comments.
Code Long And Prosper
Top comments (13)
It's important to remember that under the hood a string is just (LIKE) an array of chars. What a good use of spread!
Great introduction, Mauro!
Sometimes string manipulation can go wrong in strange ways. So it's good to know that there are alternative versions for some of these methods.
For example, the
toLocalUpperCase
andtoLocalLowerCase
methods property capitalize languages (other than, e.g., English) which can have some unexpected casing rules.Also, some Unicode glyphs need multiple character codes. If you're working with languages (and not hashing or encoding), you may want to reach for the
codePointAt
method, which handles this type of glyph correctly. If splitting or reversing a string isn't working as you'd expect, keep this method in mind.Depending on your audience and local, you may never need to reach for these methods. As your audience grows, though, using them can solve a number of strange and hard to understand bugs in string manipulation.
Cheers!
Thanks for the useful reply. This post is meant to be an introduction of the methods I used more on solving coding problems, but I am surely going to integrate it even with your suggestions. Have a nice day!
In 5th, one of the output is wrong.
This will return true.
My mistake. I forgot to change the return value after copying the line from before. Thanks, I am going to correct ;)
As I told before, thanks for this suggestion. Now a question. The problem with split() is only when it comes to split the string on any character ? or even when you need to split at white spaces to create an array of words inside a sentence with split(' ')? just to understand better this "problem"
I don't think of JavaScript as a language anymore, it's more of a vendors interpretation of an engine. I appreciate your point of view but honestly, if something behaves like something else who cares if factually not the same.
JavaScript has, as you might be aware, a specification called EcmaScript. The implementation (say v8) is indeed an interpretation of that specification, but this specification does dictate how all this is supposed to work, quite well. In this case, it even states that the specification doesn't specify how
string
s are supposed to be stored. It also specifically states that the string "elements" are the UTF-16 integers that @dominela10 speaks about.ref: String Type
However, it also describes how the string iterator is different than the array iterator. To clarify: it specifically states that the string iterator iterates over codepoints, which is the closest thing to a character JavaScript has, which is not the same as a code element. To interpret a
string
as an array is therefore something that is indeed pretty careless.ref: String Iterator
Iterators are not Arrays, Arrays are, depending on the language, iterable, or yield an iterator; strings are, depending on the language iterable, or yield an iterator; iterators are iterable.
In that aspect, @adam_cyclones you are correct that the string iterator is the same as an array iterator.
Thanks for the answer!
And what are most JavaScript engines written in?
Further to this, I am fully aware of what types exist and thier prototyping.
Thanks. I didn't know about this strange behaviour of split(). I am going to add your suggestions on the post.I learned something new and it is great. Thanks again and have a nice day!
Yes, that is what I was saying as well :)
The ref links also link to the ecma spec :D
Such string much char. Only kidding I will have a read at some point.
EcmaScript .. what's that? 🤣