Hi Friends 👋,
Welcome To Infinitbility! ❤️
To add a character in a string in javascript, just use the +
operator it will concat two strings in one string and for short syntax, you can also use the +=
operator.
let’s take an example of adding two characters in a single string.
1let name = "";23name += "Infinite";4name += " ";5name += "Ability";67console.log(name)8// 👇️ Output9// Infinite Ability
Today, I’m going to show you How do I add a character in a string in javascript, as above mentioned here, I’m going to use the +
operator to add a string to another string.
Let’s start today’s tutorial how do you add character in string in javascript?
Here we will take the example of
- add multiple strings to the string
- add an array of string to the string
- add an object of string to string
Let’s write code…
Add multiple strings to string example
To add multiple strings to a string, use the +=
operator to add n numbers of strings in a variable. (it works in case of static. )
1let name = "";23// add string how much you want4name += "Infinite";5name += " ";6name += "Ability";78console.log(name)9// 👇️ Output10// Infinite Ability
Add an array of string to the string
To add an array of strings to a string, use the for...of
loop with the +=
operator it will concat n number array elements to a single string.
1let name = "";23const names = ["Infinite", "Ability"];4for(let value of names){5 name += value;6 name += " ";7}89console.log(name)10// 👇️ Output11// Infinite Ability
If you need an array of strings as a comma-separated string just use the join()
method. it will convert your array of strings to comma-separated strings.
1const names = ["Infinite", "Ability"];2let name = names.join();34console.log(name)5// 👇️ Output6// 'Infinite,Ability'
Add object of string to string
To add an object of string to string, use for...of
loop and Object.entries()
with the +=
operator it will concat n number object elements to a single string.
1let name = "";23const nameObj = {4 firstName: "Infinite",5 lastName: "Ability",6};7for(let [key, value] of Object.entries(nameObj)){8 name += value;9 name += " ";10}1112console.log(name)13// 👇️ Output14// Infinite Ability
If you need the object of the string as a comma-separated string just uses with Object.values()
with join()
method. it will convert your array of strings to comma-separated strings.
1let name = "";23const nameObj = {4 firstName: "Infinite",5 lastName: "Ability",6};7name = Object.values(nameObj).join();89console.log(name)10// 👇️ Output11// 'Infinite,Ability'
I hope it helps you, All the best 👍.
Follow me on Twitter
Join our email list and get notified about new content
No worries, I respect your privacy and I will never abuse your email.
Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.