Corioste
Corioste

Reputation: 65

how to make the string dynamically depending in the list?

I want to make the string dynamically using user input then i want to loop this to the list of first name for example:

I have a list of this firstname

let firstnameList = ["Jan", "Mark","Doe"]

then i have this message from user input

example GUI:

enter image description here

let message = "Hello {firstname}"

then the {fistname} in the string will be replace by the names on the list

example output

message = Hello Jan 
message = Hello Mark
message = Hello Doe

Upvotes: 0

Views: 176

Answers (2)

Traidos
Traidos

Reputation: 67

You want to loop through your array like so:

let firstnameList = ["Jan", "Mark", "Doe"];
for (let firstName of firstnameList) {
    //In here you can access the current first name by using the newly created variable firstName
    console.log('Hello ' + firstName);
    // Or
    console.log(`Hello ${firstName}`);
}

Check out string concatenation and template literals if this is new to you.

To replace the placeholder like {firstname} in the message you can use

let message = 'This is {firstname} and I am hungry.'

function fillPlaceHolders(rawString) {
    return rawString.replace('{firstname}', 'my replace string');
}

console.log(fillPlaceHolders(message));

Upvotes: 1

Ali Esmailpor
Ali Esmailpor

Reputation: 1201

You can do this:

let firstnameList = ["Jan", "Mark", "Doe"];

firstnameList.map((item, index) => {
  console.log(`Hello ${item}`);
});

Upvotes: 2

Related Questions