I'm trying to find a way to separate two words with periods to match a certain character length in Javascript. For example, say I made a function where my desired length is 20 characters and entered 'Dapper' and 'Donald'. I need to find a way to pad out the string and get a result of 'Dapper........Donald'. I'm pretty lost, so I appreciate any help.
Asked
Active
Viewed 74 times
0
-
2Can you show us what you tried so far? – elclanrs Jan 16 '15 at 08:46
3 Answers
1
This should do it. Although it won't handle when the string is longer than 20 characters
function pad(one, two){
var dots = "";
while((one + dots + two).length < 20){
dots += ".";
}
return (one + dots + two);
}
alert(pad("Dapper","Donald"));

roryok
- 9,325
- 17
- 71
- 138
0
You can calculate how many dots you need, and get those from a longer string using substr
:
function padMiddle(word1, word2, len) {
var dots = len - word1.length + word2.length;
return word1 + '....................'.substr(0, dots) + word2;
}
Usage:
var padded = padMiddle('Dapper', 'Donald', 20);
To make it work for any length you could create a string by repeating the same character a number of times. See Repeat Character N Times
0
This will work:
function pad(str1, str2, maxlength) {
var lengthOf2str = str1.length + str2.length,
dots,
result;
if (maxlength > lengthOf2str) {
dots = new Array(maxlength - lengthOf2str + 1).join('.');
result = str1 + dots + str2;
} else {
result = str1 + str2;
}
return result;
}
alert(pad('Dapper', 'Donald', 20));

vk5
- 5
- 2