chacha
chacha

Reputation: 99

Javascript - replace words in string with object values

I have a an object with keys and values where the keys are variable names. e.g:

{name: 'Simon', gender: 'male', age: 43, country: 'UK'}

I also have a string/string literal where I need to replace words starting with '#' with their respective variables name. e.g

Hello my name is #name!

I'm a #age year old #gender living in the #country.

The final result would be:

Hello my name is Simon!

I'm a 43 year old male living in the UK.

Can I get some advice on how to do this in Javascript? So far I'm just iterating through the string and finding every occurrence of '#' and trying to replace it until I see the first delimeter/special char/white space etc but don't know how to put it into code.

for(let i = 0; i < string.length; i++){
   if(string[i] == '#'){
      //not sure how to complete it
   }
}

Upvotes: 2

Views: 2401

Answers (6)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

var data = {name: 'Simon', gender: 'male', age: 43, country: 'UK'}

var str_list = ["Hello my name is #name!",
                "I'm a #age year old #gender living in the #country."];

var updated_str_list = str_list
    .map(str => 
        Object.keys(data).reduce((updated_str, key) => 
            updated_str.replace(`#${key}`, data[key]), str));

console.log(updated_str_list);

Upvotes: 1

JGFMK
JGFMK

Reputation: 8904

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display the string with data substituted.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
  var str = "I'm a #age year old #gender living in the #country.";
  var dictionary = {"name": "Simon", "gender": "male", "age": 43, "country": "UK"};
  for (var key in dictionary) {
    var f = '#' + key;
    str = str.replace(f, dictionary[key]);
  }
  document.getElementById("demo").innerHTML = str;
}

</script>

</body>
</html>

Useful Stack Overflow posts:

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196197

One way would be to use a regular expression like

/#(\w+)/g

Regular expression visualization

which would find in the string all the substrings starting with # and then use the .replace method to reference the values in your object

const data = {name: 'Simon', gender: 'male', age: 43, country: 'UK'};

const template = `Hello my name is #name!
I'm a #age year old #gender living in the #country.`

const result = template.replace(/#(\w+)/g, (match,key)=>data[key]||match);

console.log(result);

Upvotes: 5

Ahed Kabalan
Ahed Kabalan

Reputation: 855

Could do in one line:

str.replace(/(^|\W)#(\w+)/g, function(_, $1, $2) { return $1 + yourObject[$2] });

Example:

var obj = {name: 'Simon', gender: 'male', age: 43, country: 'UK'};
            
var str =  "I'm a #age year old #gender living in the #country.";
var newStr = str.replace(/(^|\W)#(\w+)/g, function(_, $1, $2) { return $1 + obj[$2] });
console.log(newStr);

Upvotes: 0

Akshay Barpute
Akshay Barpute

Reputation: 73

Below code will work for you.

const keysToReplace = {name: 'Simon', gender: 'male', age: 43, country: 'UK'}
let str ='I/'m a #age year old #gender living in the #country';
Object.keys.forEach(key=>{
str = str.replace(`${key}`,keysToReplace[key]);
})

Upvotes: 0

StudioTime
StudioTime

Reputation: 23999

Template literals will help: Learn more here

// Assign variables to an object
const myData = {name: 'Simon', gender: 'male', age: 43, country: 'UK'}

// Now extract the variables as needed - google "destructuring" if this is new to you
const { name, gender, age, country } = myData;

// Then insert the variables into your string
const myString = `Hello my name is ${name}! I'm a ${age} year old ${gender} living in the ${country}`;

console.log(myString);

Upvotes: 0

Related Questions