Strings

Bashar Ayyash
2 min readAug 29, 2015

--

This is a part of Starter to ES6

Javascript strings are limited when compared with other programming languages strings objects, with new ES6 strings new functionalities, templates and and multi lines strings.

New Methods

  • includes() — returns true if the given text is found anywhere within the string or false if not.
  • startsWith() — returns true if the given text is found at the beginning of the string or false if not.
  • endsWith() — returns true if the given text is found at the end of the string or false if not.
  • repeat() — returns new string that has the original string repeated the specified number of times.

Example of using these methods:

var msg = “Hello world!”;
console.log(msg.startsWith(“Hello”)); // true console.log(msg.endsWith(“!”)); // true
console.log(msg.includes(“o”)); // true
console.log(msg.startsWith(“o”)); // false console.log(msg.endsWith(“world!”)); // true console.log(msg.includes(“x”)); // false
console.log(msg.startsWith(“o”, 4)); // true
console.log(msg.endsWith(“o”, 8)); // true console.log(msg.includes(“o”, 8)); // false
console.log(msg.repeat(2));//Hello world!Hello world!
console.log(msg.split(“ “)[0].repeat(3));// HelloHelloHello

Templates in the New Strings

In old javascript when you want to make variables values appear in a string you needed to concatenate the sting with the variables, but with ES6 strings template you don’t need to do that any more.

In old javascript:
function add(x, y){ var sum = x + y; console.log(“The result of aggregate “ + x + “ + “ + y + “= “ + sum + “.”);
}

In ES6:
function add(x,y){ let sum = x + y; console.log(`The result of aggregate ${x} + ${y} = ${sum}.`);
}

console.log(add(5,6));//The result of aggregate 5 + 6 = 11.
console.log(add(1,2));//The result of aggregate 1 + 2 = 3.

Template strings act like regular strings that are delimited by backticks (`) instead of double or single quotes which surround the text and the templates (${?})

Multi Lines String

To represent multi lines with double or single quotes you need to add (+) with each end of the string so the string will be one line, with ES6 strings just add backticks(`) at the beginning and at the end of the string.

Old javascript
var htmlString = ‘<!doctype html>\n’ + ‘<html>\n’ + ‘<head>\n’ + ‘ <meta charset=”UTF-8">\n’ + ‘ <title></title>\n’ + ‘</head>\n’ + ‘<body>\n’ + ‘</body>\n’ + ‘</html>\n’;

ES6
let htmlString = ` <!doctype html> <html> <head> <meta charset=”UTF-8"> <title></title> </head> <body> </body> </html>`;

This is a part of Starter to ES6

--

--

Bashar Ayyash

Front End Developer, I’m confident that Vue.js is as powerful as React, but way more flexible and a lot easier to learn