copenndthagen
copenndthagen

Reputation: 50742

Javascript to generate dynamic string of numbers

I have a requirement to write a function to generate the below dynamic string.

Here are some examples of what the output should look like for a function argument of 6, 5, and 4, respectively (Actually I am flexible with passing the argument).

123456789112345678921234567893123456789412345678951234567896

12345678911234567892123456789312345678941234567895

1234567891123456789212345678931234567894

The length of the output will always be a multiple of 10.

Should I use normal JS arrays OR can I use some ready jQuery methods to acheive this ?

Upvotes: 1

Views: 1260

Answers (6)

maulik sakhare
maulik sakhare

Reputation: 2047

You can use this simple logic...

var str = '123456789';
var len=5;
var out = ''
for(var i=1;i<=len;i++){out+=str+i;}
console.log(out)

Upvotes: 1

kumbhani bhavesh
kumbhani bhavesh

Reputation: 2257

Try this way

var nu=5;
for(var i=1;i<=nu;i++){

for(j=1;j<=9;j++){
console.log(j)
}
console.log(i)
}

jsbin

Upvotes: 1

Radhesh Vayeda
Radhesh Vayeda

Reputation: 911

Here is the code, I think it will help you

function dynamicNumber(n){
var s="";
for(i=1;i<=n;i++){

s=s+"123456789"+i;
}
return s;
}

Upvotes: 3

wartoshika
wartoshika

Reputation: 541

What about (ES6):

function getString(amount) {

    let sNumber = '';
    for(let i=1;i<=amount;i++) {

        sNumber += '123456789' + i;
    }
    return sNumber;
}

Upvotes: 1

Try something like this.

function generateString(l) {
  var x = "123456789",
    t = "";
  for (i = 1; i < (l + 1); i++) {
    t += x + i;
  }
  return t;
}

Example below:

function generateString(l) {
  var x = "123456789",
    t = "";
  for (i = 1; i < (l + 1); i++) {
    t += x + i;
  }
  return t;
}

console.log(generateString(6))
console.log(generateString(5))
console.log(generateString(4))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

user8233884
user8233884

Reputation:

Here is how I do it:

function dynamic_string(val){
var strin =  "123456789"
var result = ""
for(var i = 1; i <= val; i++){
  result += strin;
  result += i;
}
console.log(result)
}

dynamic_string(6)

Upvotes: 1

Related Questions