concat() and repeat() (insert echoing "repeat" here)
The JavaScript String Methods series
- Part 0 - toUpperCase() and toLowerCase()
- Part 1 - split() and join()
- Part 2 - slice(), substring(), substr()
- Part 3 - charAt(), charCodeAt(), fromCharCode(), at()
- You are herePart 4 - concat() and repeat()
- Part 5 - search() and includes()
- Part 6 - indexOf() and lastIndexOf()
- Part 7 - endsWith() and startsWith()
- Part 8 - match() and matchAll()
- Part 9 - replace() and replaceAll()
- Part 10 - trim(), trimEnd() and trimStart()
- Part 11 - padStart() and padEnd()
Skip to:
Concat
concat()
will take N strings as parameters, combine them, and return the combined text. It works pretty much like using the +
operator, but this time around if the arguments are not really Strings they will be converted directly to strings.
let string1 = 'Welcome aboard'
let string2 = 'Choo choo shoe'
string1.concat(' on the ', string2)
//output: 'Welcome aboard on the Choo choo shoe'
''.concat(1,2,3)
//output: '123'
''.concat(1,false)
//output: '1false'
Compare the code above with the next one. In the first concat()
you're passing a single parameter, which will be resolved and THEN added to ''.
''.concat(1+false)
//output: '1'
''.concat(1+true)
//output: '2'
''.concat(1,true)
//output: '1true'
console.log(1 + false)
//output: 1
console.log(1 + false + '')
//output: '1'
Repeat
Can you repeat strings using concat()
? Well... yeeeeah...
Take a look:
let string = 'Choo choo shoe'
''.concat(string, string, string)
//output: 'Choo choo shoeChoo choo shoeChoo choo shoe'
It works, sure. But then you have repeat()
.
It takes a single parameter, an integer between 0 and INFINITY which will be the number of times your string will be repeated.
let string = 'Choo choo shoe'
string.repeat(3)
//output: 'Choo choo shoeChoo choo shoeChoo choo shoe'
Much more train noise, much cleaner looking.
If you try repeat()
passing 0 as a parameter, it will return an empty string. Same thing will happen if you don't feed it any parameter, or something that can't be converted into an integer.
If your repeat()
count is a floating point number rather than an integer, only the integer will be considered.
let string = 'Choo choo shoe'
string.repeat(0)
//output: ''
string.repeat('2')
//output: 'Choo choo shoeChoo choo shoe'
string.repeat('Yay!')
//output: ''
string.repeat()
//output: ''
string.repeat(3.14)
//output: 'Choo choo shoeChoo choo shoeChoo choo shoe'
So it's pretty lenient, but it will throw an error if you try a negative number!
"Hi, I'm on TV!".repeat('-2')
//output: Uncaught RangeError: Invalid count value: -2
Practice
If you're up for a challenge, check this 7-kyu CodeWars kata!
For extra practice, jskatas.org has interesting exercises in the form of tests.