Javascript String To Array Example


Share:
Published By: Admin, Published On: Apr 10, 2021, Category: Javascript

Hello Friends,

Now let's see example of how to convert string to array in javascript. Here you will learn how to use javascript string to array conversion. We will use how to convert string to array in javascript. This is a short guide on convert string to array. Let's get started with how to convert string to array in javascript.

Here i will give you many example how you can convert string to array in javascript.

Example: 1
<!DOCTYPE html>
<html>
	<head>
	   <title>Javascript - How to convert string to array?-MyWebtuts.com</title>
	</head>
	<body>

		<script>

			const string = 'hi there';
			const usingSplit = string.split('');
			const usingSpread = [...string];
			const usingArrayFrom = Array.from(string);
			const usingObjectAssign = Object.assign([], string);

			console.log(usingSplit);
			
		</script>

	</body>
</html>
Output: 1
	(8) ["h", "i", " ", "t", "h", "e", "r", "e"]
	0: "h"
	1: "i"
	2: " "
	3: "t"
	4: "h"
	5: "e"
	6: "r"
	7: "e"
length: 8
Example: 2
<!DOCTYPE html>
<html>
	<head>
	   <title>Javascript - How to convert string to array?-MyWebtuts.com</title>
	</head>
	<body>

	<script>

		const string = 'split-by-dash';
		const usingSpread = [...string];
		const usingArrayFrom = Array.from(string);
		const usingObjectAssign = Object.assign([], string);

		console.log(usingArrayFrom);

	</script>

	</body>
</html>
Output: 2
	(13) ["s", "p", "l", "i", "t", "-", "b", "y", "-", "d", "a", "s", "h"]
	0: "s"
	1: "p"
	2: "l"
	3: "i"
	4: "t"
	5: "-"
	6: "b"
	7: "y"
	8: "-"
	9: "d"
	10: "a"
	11: "s"
	12: "h"
	length: 13

It will help you....

Share: