r/javaScriptStudyGroup • • Nov 08 '17

Writing a Script that Prints out 1-500 While Concatenating it to a String

Ok. The title is not so bright. This is what I want to achieve:

The url +[1-500]+.jpg printed out

www.example.com/img/1.jpg
www.example.com/img/2.jpg
www.example.com/img/3.jpg
...
...
...
www.example.com/img/400.jpg

How I think of going about it

str1 = "www.example.com/img/
str2 = ?
str3 = ".jpg"
res = concat of str1+str2+str3

Str2 is the function that prints out 1-500. I cannot figure it out. Help!

I just started learning Javascript. From a Literature background. I thought I should let that out.

1 Upvotes

4 comments sorted by

2

u/bluemonkey10 Nov 08 '17

Try implementing a for loop and print/concat the string within it.

2

u/atreyoukilis Nov 09 '17

Blue monkey has the correct idea, here's the implementation if you're curious:

let str1 = "www.example.com/img/"
let str3 = ".jpg"

function printUrls(){
  for (let i = 1; i<501; i++){
    console.log(str1 + i + str3)
  }
}

2

u/bluemonkey10 Nov 10 '17

Exactly what I was thinking :)

1

u/T_O_beats Nov 27 '17 edited Nov 27 '17

I made an es6 solution that you could extend if you needed

const options = {
    path: 'www.example.com/img',
    extension: 'jpg',
    classNames: ['img', 'img-responsive']
}

const linkArrayer = (startingNumber = 0, count = 1, linkArray = [], {
    path,
    extension,
    classNames = [] } = {...options}) => {

    const totalImageCount = count + 1
    const createLink = (i) => {
        return `${path}/${i}.${extension}`
    }

    for (let i = startingNumber; i < totalImageCount; i++) {
        let imageLink = createLink(i)
        linkArray.push(imageLink)
    }

    return linkArray;

}
console.log(linkArrayer(0, 200))