Reputation:
I'm trying to create this program to prompt the user for two words and then prints out both words on one line. The words will be separated by enough dots so that the total line length is 30. I've tried this and cannot seem to get it.
<html>
<head>
<title>Lenth of 30</title>
<script type="text/javascript">
//Program: Lenth of 30
//Purpose: The words will be separated by enough dots so that the total line length is 30:
//Date last modified: 4/11/12
var firstword = ""
var secondword = ""
firstword = prompt("Please enter the first word.")
secondword = prompt("Please enter the second word.")
document.write(firstword + secondword)
</script>
</head>
<body>
</form>
</body>
</html>
An example:
Enter first word:
turtle
Enter second word
153
(program will print out the following)
turtle....................153
Upvotes: 1
Views: 359
Reputation: 149594
Here’s a generic solution that shows you how to do this:
function dotPad(part1, part2, totalLength) {
// defaults to a total length of 30
var string = part1 + part2,
dots = Array((totalLength || 30) + 1).join('.');
return part1 + dots.slice(string.length) + part2;
}
Use it as follows:
dotPad('foo', 'bar'); // 'foo........................bar'
In your case:
dotPad(firstword, secondword);
This is a very simplistic solution — if needed, verify that the concatenated form of the input strings is shorter than length
characters.
Upvotes: 3
Reputation: 20235
You can get the amount of dots using some simple math. Subtract each word length from 30.
var dotLen = 30 - firstword.length - secondword.length;
document.write( firstword );
while ( dotLen-- ) {
document.write( "." );
}
document.write( secondword );
EDIT: I actually like Mathias's solution better. But you can make it simpler:
document.write( firstword + Array( 31 - firstword.length - secondword.length ).join( '.' ) + secondword );
Upvotes: 0
Reputation: 25676
You can use the length
property to determine the length of each string, and then calculate the number of .
s that you need to add.
Upvotes: 0
Reputation: 120198
you need to calculate how many periods you need.
var enteredLength = firstword.length + secondword.length;
var dotCount = 30 - enteredLength;
var dots = "";
for(var i = 0; i < dotCount; i++) dots += '.';
you can take if from there....
Upvotes: 1
Reputation: 32542
Subtract the length of the first word and the length of the second word from 30, and print out that many dots in a for loop.
Upvotes: 0