How to copy a string in TypeScript

10 Answers

0 votes
// Copy using simple assignment

let src: string = "Programming is fun";

let dest: string = src; // Same reference

console.log(dest);


/*
run:

Programming is fun

*/

 



answered 14 hours ago by avibootz
0 votes
// Copy using template literal

let src: string = "Programming is fun";

let dest: string = `${src}`;

console.log(dest);




/*
run:

Programming is fun

*/

 



answered 14 hours ago by avibootz
0 votes
// Copy using String() constructor

let src: string = "Programming is fun";

let dest: string = String(src);

console.log(dest);




/*
run:

Programming is fun

*/

 



answered 14 hours ago by avibootz
0 votes
// Copy using new String() wrapper

let src: string = "Programming is fun";

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

console.log(dest);




/*
run:

Programming is fun

*/

 



answered 14 hours ago by avibootz
0 votes
// Copy using slice()

let src: string = "Programming is fun";

let dest: string = src.slice(0);

console.log(dest);



/*
run:

Programming is fun

*/

 



answered 14 hours ago by avibootz
0 votes
// Copy using substring()

let src: string = "Programming is fun";

let dest: string = src.substring(0);

console.log(dest);




/*
run:

Programming is fun

*/

 



answered 14 hours ago by avibootz
0 votes
// Copy using split and join

let src: string = "Programming is fun";

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

console.log(dest);




/*
run:

Programming is fun

*/

 



answered 14 hours ago by avibootz
0 votes
// Copy using Array.from

let src: string = "Programming is fun";

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

console.log(dest);




/*
run:

Programming is fun

*/

 



answered 14 hours ago by avibootz
0 votes
// Copy using spread operator

let src: string = "Programming is fun";

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

console.log(dest);




/*
run:

Programming is fun

*/

 



answered 14 hours ago by avibootz
0 votes
// Copy using manual loop

let src: string = "Programming is fun";

let dest: string = "";

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

console.log(dest);




/*
run:

Programming is fun

*/

 



answered 14 hours ago by avibootz

Related questions

6 answers 10 views
7 answers 9 views
8 answers 21 views
8 answers 16 views
7 answers 13 views
11 answers 23 views
...