This is the second article highlighting some of the latest improvement issued in the most recent released of the ECMAscript for javascript string.
The first article covered classes and is named: Javascript Class: ECMAScript standards.
Javascript String
String is one of the most primitive object and most used in any programming language. It the most recent ECMAscript releases (starting from the 2015), javascript string have received some updated and improvement that will support developers in their usage.
This article will cover changes like templates literals, replacements, concatenation and tagged templates literals by offering brief descriptions and code snippets where appropriate.
Template literals
Template literals also known as “template strings”, can be accessed by the use of the back-tick (`) characters, differently from the basic strings that are initialised with single or double quotes.
This are very powerful as they enable string manipulation without the overhead that that we have had to use until now. The first feature of template literals that we are going to cover is the ability to specify multi-line strings.
Multi-line String
Javascript multi-line string have until recent being defined by ending the string with “/n” and a “+” sign, Like the example below.
console.log('This is my first line 1\n' + 'and this is my second');
This code, even if probably quite easy to write, it is not easy to maintain and not nice to read (breaking one of the rule of clear code).
If declaring a string with template literals notation, you will actually be able to define multi line string without the need of any additional character. The example below will actually output the same as the one previously shown.
console.log(`This is my first line 1 and this is my second`);
String replacement “embedding”
String embedding or replacement occurs when we try to dynamically create a string by adding an expression or a variable within it. This is personally one of the feature that I really hate in Javascript. Most of the common languages had string manipulations methods and finally, this feature are also available to the Javascript developers.
Prior to the template literals you may have use the following to create a dynamic javascript string.
var a = "Fifteen"; var b = 5; console.log(a + 'is ' + (b * 3) + ' and\nnot ' + (b * 2) + '.'); // "Fifteen is 15 and // not 10."
The above is not only quite tricky to write as it require lots of parenthesis and quotes, but it is also very hard to read compared to the following, that as with all the other examples, will output perfectly the same.
var a = 'Fifteen'; var b = 5; console.log(`${a} is ${b *3} and not ${b * 2}.`); // "Fifteen is 15 and // not 10."
Tagged template literals
This is an advanced for of template literals. It will enable you to create a function that can be used to parse you template literals.
The return value of this function does not have to be a string, but in the following example we show the “basic” feature.
function tagExample(strings, valueOne, valueTwo){ //the strings is the array of strings, each item separated by one of the value let firstPart = strings[0]; let secondPart = strings[1]; let thirdPart = ""; if(valueOne >= valueTwo){ thirdPart = "therefore younger than me." }else{ thirdPart = "therefore older than me." } return `${firstPart} ${valueOne} ${secondPart} ${valueTwo} ${thirdPart}`; } tagExample`I am ${myAge}while my brother is ${myBrotherAge}` //OUTPUT "I am 15 while my brother is 30 therefore older than me."
String prototype methods
The following paragraphs are going to cover useful methods that have been released since the ECMAscript 2015.
javascript string includes
This new method is surely going to put a smile on your face. As a developer, I have used the following OLD method many times, and every time I had to go through over at least twice to make sure that it was returning the correct behaviour.
The include method will allow you to search for a specific string and will return the position. This was previously done using the indexOf() method like the example below.
var stringToSearch = "This is a very long string"; stringToSearch.indexOf("string") !== -1; //true
We are now able to easily obtain the same result using the includes() method. This method also allows us to pass a second paramether that specifies where the string starts.
var stringToSearch = "This is a very long string"; stringToSearch.includes("string"); //true
javascript string repeat
The name of this method is self explanatory. It allows you to repeat a specific string for a X number of times
let var1 = "etc "; var1.repeat(3); //etc etc etc
javascript string startsWith and endsWith
This helpers return a Boolean value and also support a second parameter that is the position to where the string check starts.
var string1 = "Start with a simple word and finish with another."; string1.startsWith("simple ", 13); //true string1.endsWith("Start"); //false
Browser support
At time of writing, the features covered in this article are largely supported in all the main used browsers ( includes mobiles browsers), with the only exception of IE11 and is still not supporting this features as showed by the graph below or as it can be found in by following this link to caniuse.com website.
Conclusion
Even if the above feature may not be the most exiting introduced by the ECMAscript standards, they are surely going to make your day to day life a lot easier. Productivity can surely increase and this small methods will not only make you develop faster, but will also make your code more readable that is what most of us hope to achieve.