- Previous
- Next
- JavaScript function receives an input string and a number as inputs.
- If the number is greater than or equal to 0, it is repeated
number- 1
times. - If the number is less than 0, it is string is set to
empty.
- Output the results.
In JavaScript, there are several in-built functions to manipulate strings. One of them is String.prototype.repeat()
function. In this tutorial, you will write a program that will repeat a string for a given number of times.
The steps that this program follows is given below:
The program uses 2 textbox control
for inputs, 1 h1 tag
for output, 2 buttons - clear and repeat
to clear the textboxes and invoke the JavaScript function respectively.
Program Code: Repeat A String
<!DOCTYPE html>
<html>
<head>
<title>Repeat A String</title>
<meta charset="utf-8">
<style>
main{
width:40%;
padding:2%;
margin:10% auto;
background:lime;
text-align:center;
}
#input,#inputTwo{
padding:10px;
width:200px;
background:whitesmoke;
margin:auto;
font-size:16px;
}
button{
padding:10px;
margin:10px;
}
</style>
</head>
<body>
<main>
<h1 id="out">Output here</h1>
<p>Program to repeat a string based on a input number.
Does not use String.prototype.repeat() javascript function.</p>
<input type="text" id="input" value="Enter string" /><br/>
<input type="text" id="inputTwo" value="Enter Number"/><br/>
<button onclick="repeatString()">Repeat String</button>
<button onclick="MyClear()">Clear</button>
</main>
<script>
function repeatString() {
// repeat after me
var str = document.getElementById("input").value;
var num = parseInt(document.getElementById("inputTwo").value);
let tempStr = str;
let N = num - 1;
for(let i = 0;i < N;i++){
if(N >= 0)
{
str = str + tempStr;
}
}
if(N < 0)
{
str = "";
}
document.getElementById("out").innerHTML = str;
}
function MyClear() {
document.getElementById("input").value = "";
document.getElementById("inputTwo").value = "";
document.getElementById("out").innerHTML = "Output here";
}
</script>
</body>
</html>
Note that the HTML elements are accessed using getElementById
object. It will be used to access the string input and display the output string.
Also, to clear the textboxes.