How to copy a string in JavaScript

10 Answers

0 votes
// Copy using simple assignment

let src = "Programming is fun";

let dest = src; // Same reference

console.log(dest);


/*
run:

Programming is fun

*/


answered 2 days ago by avibootz
0 votes
// Copy using template literal

let src = "Programming is fun";

let dest = `${src}`;

console.log(dest);



/*
run:

Programming is fun

*/

 



answered 2 days ago by avibootz
0 votes
// Copy using String constructor

let src = "Programming is fun";

let dest = String(src);

console.log(dest);



/*
run:

Programming is fun

*/

 



answered 2 days ago by avibootz
0 votes
// Copy using new String() wrapper

let src = "Programming is fun";

let dest = new String(src).toString();

console.log(dest);



/*
run:

Programming is fun

*/

 



answered 2 days ago by avibootz
0 votes
// Copy using slice()

let src = "Programming is fun";

let dest = src.slice(0);

console.log(dest);



/*
run:

Programming is fun

*/

 



answered 2 days ago by avibootz
0 votes
// Copy using substring()

let src = "Programming is fun";

let dest = src.substring(0);

console.log(dest);




/*
run:

Programming is fun

*/

 



answered 2 days ago by avibootz
0 votes
// Copy using split and join

let src = "Programming is fun";

let dest = src.split("").join("");

console.log(dest);



/*
run:

Programming is fun

*/

 



answered 2 days ago by avibootz
0 votes
// Copy using Array.from

let src = "Programming is fun";

let dest = Array.from(src).join("");

console.log(dest);




/*
run:

Programming is fun

*/

 



answered 2 days ago by avibootz
0 votes
// Copy using spread operator

let src = "Programming is fun";

let dest = [...src].join("");

console.log(dest);



/*
run:

Programming is fun

*/

 



answered 2 days ago by avibootz
0 votes
// Copy using manual loop

let src = "Programming is fun";

let dest = "";

for (let ch of src) {
    dest += ch;
}

console.log(dest);



/*
run:

Programming is fun

*/

 



answered 2 days ago by avibootz

Related questions

6 answers 18 views
7 answers 18 views
8 answers 26 views
8 answers 24 views
7 answers 18 views
11 answers 25 views
...