amirh
amirh

Reputation: 3

Insert space as a given amount in JS

I have a variable number (for example 3) and two strings. How I can put 3 spaces between two string? output better to be alert like

var number=3;var string1="hello";var string2="world";alert(string1+"   "+string 2);

note that number must get with prompt.

Upvotes: 0

Views: 232

Answers (1)

Amit Joki
Amit Joki

Reputation: 59292

You can make use of Array constructor and prompt

var num = Number(prompt("Enter the number")); // fails if not number
alert(string1 + (Array(num + 1).join(" ")) + string2);

What Array(num + 1).join(" ") does is, it creates an array of length of the number inputted by the user + 1 and joins it by " " using Array.join

Also you can do the below as per @FabrizioCalderan. Thanks mate!

alert([string1, string2].join(Array(num + 1).join(' ')));

Upvotes: 4

Related Questions