AppDividend
Latest Code Tutorials

Javascript String Slice Example | String.prototype.slice() Tutorial

0

Javascript String Slice Example | String.prototype.slice() Tutorial is today’s topic. The slice() method extracts a section of the string and returns it as the new string, without modifying an original string. We can use the startIndex and endIndex parameters to specify the part of the string you want to extract. The first character has position 0; the second has position 1, and so on. You can use the negative number to select from an end of the string.

Javascript String Slice Example

The changes to the text in one string do not affect the other string. 

The syntax for string slice method is following.

string.slice(startIndex, endIndex)

The javascript string slice() method extracts up to but not including the endIndex. That means string.slice(1, 6) extracts the second character through the sixth character (characters indexed 1, 2, 3, 4, 5).

// app.js

let str = 'Obama was US president';
let result  = str.slice(2, 9);
console.log(result);

 

Javascript String Slice Example | String.prototype.slice() Tutorial

Using slice() method with negative indexes

The following example uses slice() methods with negative indexes.

// app.js

let str1 = 'Trump is current US president';
let r1 = str1.slice(-6, -1);
console.log(r1);

 

String.prototype.slice() Tutorial

Pass only one parameter index

If we pass only startIndex, then it will extract the part of the string from the startIndex to the end of the string.

// app.js

let str1 = 'Trump is current US president';
let r1 = str1.slice(1);
console.log(r1);

Save the file and run the javascript file.

 

Javascript String Slice Example

More Examples

Extract the whole string:

// app.js

let str2 = "Hakuna Matata";
let res2 = str2.slice(0);
console.log(res2);

 

Extract the whole string

Extract only the last character.

// app.js

let str3 = "Hakuna Matata";
let res3 = str3.slice(-1);

console.log(res3);

Extract only the last character

 

Finally, Javascript String Slice Example | String.prototype.slice() Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.