How to slice (copy) out a piece of an string into a new string in JavaScript

5 Answers

0 votes
var s1 = "The worlds most popular Programming Q&A";

// string.slice(start-index, end-index)

var s2 = s1.slice(4, 10); 
 
document.write(s1);
document.write("<br />");
document.write(s2);
                  
/*
run:

The worlds most popular Programming Q&A  // s1
worlds                                   // s2
 
*/

 



answered Jun 9, 2015 by avibootz
0 votes
var s1 = "The worlds most popular Programming Q&A";

// string.slice(start-index, end-index)

var s2 = s1.slice(4); 
 
document.write(s1);
document.write("<br />");
document.write(s2);
                  
/*
run:

The worlds most popular Programming Q&A // s1
worlds most popular Programming Q&A     // s2
 
*/

 



answered Jun 10, 2015 by avibootz
0 votes
var s1 = "The worlds most popular Programming Q&A";

// string.slice(start-index, end-index)

var s2 = s1.slice(-3); 
 
document.write(s1);
document.write("<br />");
document.write(s2);
                  
/*
run:

The worlds most popular Programming Q&A  // s1
Q&A                                      // s2
 
*/

 



answered Jun 10, 2015 by avibootz
0 votes
var s1 = "The worlds most popular Programming Q&A";

// string.slice(start-index, end-index)

var s2 = s1.slice(-15, -4); 
 
document.write(s1);
document.write("<br />");
document.write(s2);
                  
/*
run:

The worlds most popular Programming Q&A  // s1
Programming                              // s2
 
*/

 



answered Jun 10, 2015 by avibootz
0 votes
var s1 = "The worlds most popular Programming Q&A";

// string.substr(start-index, length)

var s2 = s1.substr(4, 6); 
 
document.write(s1);
document.write("<br />");
document.write(s2);
                  
/*
run:

The worlds most popular Programming Q&A // s1
worlds                                  // s2
 
*/

 



answered Jun 10, 2015 by avibootz
...