Friday, February 17, 2017

ES6 - New String Methods

Following is a list of methods with their description.
Sr.No Method & Description
1 String.prototype.startsWith(searchString, position = 0) Returns true if the receiver starts with searchString; the position lets you specify where the string to be checked starts.

2 String.prototype.endsWith(searchString, endPosition = searchString.length) Returns true if the receiver starts with searchString; the position lets you specify where the string to be checked starts.
3 String.prototype.includes(searchString, position = 0) Returns true if the receiver contains searchString; position lets you specify where the string to be searched starts.
4 String.prototype.repeat(count) Returns the receiver, concatenated count times.

Template Literals

Template literals are string literals that allow embedded expressions. Templatestrings use back-ticks (``) rather than the single or double quotes. A template string could thus be written as −
var greeting = `Hello World!`; 

String Interpolation and Template literals

Template strings can use placeholders for string substitution using the ${ } syntax, as demonstrated.
Example 1
var name = "Brendan"; 
console.log('Hello, ${name}!');
The following output is displayed on successful execution of the above code.
Hello, Brendan!
Example 2: Template literals and expressions
var a = 10; 
var b = 10; 
console.log(`The sum of ${a} and ${b} is  ${a+b} `);
The following output is displayed on successful execution of the above code.
The sum of 10 and 10 is 20 
Example 3: Template literals and function expression
function fn() { return "Hello World"; } 
console.log(`Message: ${fn()} !!`);
The following output is displayed on successful execution of the above code.
Message: Hello World !!

Multiline Strings and Template Literals

Template strings can contain multiple lines.
Example
var multiLine = ' 
   This is 
   a string 
   with multiple 
   lines'; 
console.log(multiLine)
The following output is displayed on successful execution of the above code.
This is 
a string 
with multiple 
line

String.raw()

ES6 includes the tag function String.raw for raw strings, where backslashes have no special meaning. String.raw enables us to write the backslash as we would in a regular expression literal. Consider the following example.
var text =`Hello \n World` 
console.log(text)  

var raw_text = String.raw`Hello \n World ` 
console.log(raw_text)
The following output is displayed on successful execution of the above code.
Hello 
World 
Hello \n World

String.fromCodePoint()

The static String.fromCodePoint() method returns a string created by using the specified sequence of unicode code points. The function throws a RangeError if an invalid code point is passed.
console.log(String.fromCodePoint(42))        
console.log(String.fromCodePoint(65, 90))
The following output is displayed on successful execution of the above code.
* 
AZ

No comments:

Post a Comment