Subscribe to my email list now at http://jauyeung.net/subscribe/
Follow me on Twitter at https://twitter.com/AuMayeung
Many more articles at https://medium.com/@hohanga
Strings are an important global object in JavaScript. They represent a sequence of characters. They can be used by various operators, like comparison operators, and there are various methods that can be used to manipulate them. There are different ways to manipulate strings, look up parts of a string in various positions, and trim and replace strings. With each release of the JavaScript specification, more methods are added to make string search and manipulating easier than ever.
Instance Methods Continued
Instance methods of a string are called on the string literal or the string object. They do something to the instance of the string that’s being called on. We continue the list from part 1.
String.normalize()
The normalize
method returns the Unicode Normalization Form of a given string. It will convert non-string arguments into a string before conversion. For example, if we have:
const first = '\\u00e5'; // "å"
const second = '\\u0061\\u030A'; // "å"
Then we call the normalize
method in each string to normalize them into the same character code:
first.normalize('NFC') === second.normalize('NFC')
The code above will evaluate to true
since we normalized the strings to the same character code. However, if we didn’t call normalize
:
first === second
Then the code above would return false
. If we run console.log
on both strings to get their character codes like in the code below:
console.log(first.normalize('NFC').charCodeAt(0));
console.log(second.normalize('NFC').charCodeAt(0));
We get 229 for the first characters for both strings since they’re the same after normalization. On the other hand, if we run it before normalization with normalize
like in the code below:
console.log(first.charCodeAt(0));
console.log(second.charCodeAt(0));
We get that the first string logs 229 and the second logs 97.
String.padStart()
The padStart()
function pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.
The function takes 2 parameters. The first is the target length of your string. If the target length is less than the length of your string, then the string is returned as-is. The second parameter is the string that you want to add the padding with. It’s an optional parameter and it defaults to ' '
if nothing is specified.
For example, we can write the following:
'def'.padStart(10); // " def"
'def'.padStart(10, "123"); // "1231231def"
'def'.padStart(6,"123465"); // "abcdef"
'def'.padStart(8, "0"); // "00000def"
'def'.padStart(1); // "def"
Note that each string is filled up to the target length with the string in the second argument. The whole string in the second argument may not always be included. Only the part that lets the function fills the string up to the target length is included.
String.padEnd()
The padEnd()
function pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the end of the current string.
The function takes 2 parameters. The first is the target length of your string. If the target length is less than the length of your string, then the string is returned as-is. The second parameter is the string that you want to add the padding with. It’s an optional parameter and it defaults to ' '
if nothing is specified.
For example, we can write the following:
'def'.padEnd(10); // "def "
'def'.padEnd(10, "123"); // "def1231231"
'def'.padEnd(6,"123465"); // "defabc"
'def'.padEnd(8, "0"); // "def00000"
'def'.padEnd(1); // "def"
String.repeat()
To use the repeat
function, you pass in the number of times you want to repeat the string as an argument. It returns a new string.
For example:
const hello = "hello";
const hello5 = hello.repeat(5);
console.log(hello5); // "hellohellohellohellohello"
String.replace()
The replace()
function included with strings is useful for replacing parts of strings with another. It returns a new string with the string after the substring is replaced.
Example:
const str = "Hello Bob";
const res = str.replace("Bob", "James"); // 'Hello James'
replace()
can also be used to replace all occurrences of a substring.
For example:
const str = "There are 2 chickens in fridge. I will eat chickens today.";
const res = str.replace(/chickens/g, "ducks"); // "There are 2 chickens in fridge. I will eat chickens today."
If the first argument is a regular expression that searches globally, it will replace all occurrences of the substring.
String.search()
search
gets the position of the substring passed into the function. It returns -1 if the substring is not found in the string.
Example:
const str = "Hello";
const res = str.search('H'); // 0
String.slice()
The slice
method extracts a part of the string and returns a new string. We can pass in both positive and negative numbers. If the range is positive, then the returned substring will start and end with the indexes that are passed in. If they’re negative, then the starting index starts from the last character of the string with index -1 and then count backward back to the start of the string, going down by 1 when a character is left of another character. If the second argument is omitted, then it’s assumed to be the index of the last character of the string.
For example, we can write:
const str = 'Try not to become a man of success. Rather become a man of value.';
console.log(str.slice(31));
// output: "ess. Rather become a man of value."
console.log(str.slice(4, 19));
// output: "not to become a"console.log(str.slice(-4));
// output: "lue."console.log(str.slice(-9, -5));
// output: "of v"
String.startsWith()
startsWith
checks if a string starts with the substring you pass in.
For example:
const str = "Hello world.";
const hasHello = str.startsWith("Hello"); // trueconst str2 = "Hello world.";
const hasHello2 = str.startsWith("abc"); // false
String.split()
The split
method splits a string into an array of substrings. The split
method can split a string using a regular expression as the delimiter. For example, we can write:
const str = 'The 1 quick 2 brown fox jump.';
const splitStr = str.split(/(\\d)/);console.log(splitStr);
// gets ["The ", "1", " quick ", "2", " brown fox jump."]
This splits a sentence into an array of strings with the numbers separating the words. It can also take a string as the delimiter for separating the string like in the following example:
const str = 'The 1 quick 2 brown fox jump.';
const splitStr = str.split(' ');console.log(splitStr);
// gets ["The", "1", "quick", "2", "brown", "fox", "jump."]
It can also take an array of strings as separators of the given string instance. For example:
const str = 'The 1 quick 2 brown fox jump.';
const splitStr = str.split([' ']);
console.log(splitStr);
// gets ["The", "1", "quick", "2", "brown", "fox", "jump."]
String.substr()
JavaScript strings have a substr
function to get the substring of a string.
It takes a starting index as the first argument and a number of characters from the start index, and so on as the second argument.
It can be used like this:
const str = "Hello Bob";
const res = str.substr(1, 4); // ello
String.substring()
JavaScript strings also has a substring
function that takes the start and end index as two arguments and returns a string with the ones between the start and end indices.
The start index is included but the end index is excluded.
Example:
const str = "Hello Bob";
const res = str.substring(1, 3); // el
String.toLocaleLowerCase()
Converts a string to lowercase, according to the locale of your browser. The new string is returned instead of modifying the original string.
For example:
const str = "Hello Bob!";
const res = str.toLocaleLowerCase(); // hello bob!
String.toLocaleUpperCase()
Converts a string to uppercase, according to the locale of your browser. The new string is returned instead of modifying the original string.
For example:
const str = "Hello Bob!";
const res = str.toLocaleUpperCase(); // 'HELLO BOB!'
String.toLowerCase()
Converts a string to lowercase. The new string is returned instead of modifying the original string.
For example:
const str = "Hello Bob!";
const res = str.toLocaleLowerCase(); // 'hello bob!'
String.toUpperCase()
Converts a string to uppercase. The new string is returned instead of modifying the original string.
For example:
const str = "Hello Bob!";
const res = str.toLocaleUpperCase(); // 'HELLO BOB!'
String.trim()
Remove starting and ending white space from a string.
For example:
const str = " Hello Bob! ";
const res = str.trim(); // 'Hello Bob!'
String.trimStart()
Now the string object has a trimStart()
function to trim the beginning whitespace of a string. There’s also a trimLeft()
method which is an alias to this method.
For example, we can write:
let message = ' Hi! How\'s it going? ';
console.log(message);// We get ' Hi! How's it going? 'let message = ' Hi! How\\'s it going? ';
console.log(message.trimStart());// We get 'Hi! How's it going? '
As we can see, the whitespace on the left side is gone. We can do the same thing with trimLeft()
:
let message = ' Hi! How\\'s it going? ';
console.log(message.trimLeft());// We get 'Hi! How's it going? '
Note that a new string is returned with trimStart
or trimLeft
, so the original string stays intact. This prevents us from mutating the original string, which is handy for preventing mistakes from accidentally mutating objects.
String.trimEnd()
The trimEnd
method removes whitespace from the right end of the string. trimRight
is an alias of the trimEnd
method. For example, we write:
let message = ' Hi! How\'s it going? ';
console.log(message);
// We get ' Hi! How's it going? '
let message = ' Hi! How\'s it going?';
console.log(message.trimEnd());
// We get ' Hi! How's it going?'
Note that a new string is returned with trimEnd
or trimRight
, so the original string stays intact. This prevents us from mutating the original string, which is handy for preventing mistakes from accidentally mutating objects.
String.valueOf()
With the valueOf
method, we can convert a string object into a primitive string. For example, we can write:
const sPrim = 'foo';
const sObj = new String(sPrim);
console.log(typeof sPrim);
console.log(typeof sObj.valueOf());
Then we get that both console.log
statements would show ‘string’.
Conclusion
Strings are an important global object in JavaScript. It represents a sequence of characters. It has methods to manipulate strings, look up parts of a string in various positions, and trim and replace strings. With each release of the JavaScript specification, more methods are added to make string search and manipulating easier than ever.
Top comments (13)
I feel like a good way to improve this article would have been linking to the MDN documentation for each method. Also, in the first method you discuss, normalize, you do not explain the parameters at all. Explaining why you pass 'NFC' and what the other acceptable forms are and the differences between them would've been good.
All in all though it is a good article and I am impressed at how fast you are churning them out since I started following you. Very productive!
Thanks. That's not a bad idea
I also wanted to say that there really is no reason I can think of to ever use the String constructor
new String('...')
over a string primitive. The valueOf method is pretty much only for use internally by JavaScript, and is rarely if ever used in explicitly in production code. I don't think it is a good idea to have an example using the String constructor without also explaining why they most likely will never/should never use it.100 percent agree with that.
A string constructed with the constructor has type object which is confusing.
There is no benefit and its tricks people
A thorough overview!
I did want to point out that
.split
does not know how to use an array of strings as separators. Your example works because any object passed as a first argument to.split
is converted to a string first. As it happens, the stringified form of[' ']
is' '
, so this works, but as soon as you add a second element to the array, you would get very different results -- for example,['a', 'b']
stringifies to the three-character delimiter'a,b'
.A few other bug fixes:
.split
example with a regex incorrectly escapes the\d
, which isn't necessary in a regex literal (but would be needed in a string argument to thenew RegExp
constructor)^ this is actually a very interesting use of a regex split, because normally the sequence captured by the regex is not included in the output array. However, because you use capture-group parentheses in your regex --
(\d)
instead of\d
-- the capture-group sequence is spliced into the output array.Thanks for looking at the examples.
I'll check them later.
Thanks for this helpful article,
some of these methods I never used till now, so I had to try them out immediately :-)
but since I tried your examples noticed some small mistakes in the comments within your source code which might confuse people
In .padStart and .padEnd your comment says the string was padded with abcdef instead of 123456 in the third example of both.
And after replacing chicken with duck, it still says chicken in the comment
But really thanks for the article
Regards
Thanks for reading and catching those typos.
I'll fix them.
If you haven't tried quokka out it can make these types of examples read a bit cleaner, I didn't know you could use regex in split! Thanks for the info
Thanks so much for reading!
It's been almost one year of using js on my projects but i barely used or seen some of the above js methods. You better explain with understanding example.
Thank you!
Hey!
In the String Repeat function there is a typo.
A is not defined, therefore it should be: const hello5 = hello.repeat(5);
Cherrs.
Thanks for catching that. I'll fix this.