2

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
   }
}
3
  • Look at the replace method Commented Dec 24, 2019 at 12:56
  • ^ Especially the version where you use a regular expression and pass it a function as the second parameter (but there has to be a dupe target for this...) Commented Dec 24, 2019 at 12:57
  • Like this one? How to replace specific parts in string with javascript with values from object Commented Dec 24, 2019 at 13:00

6 Answers 6

6

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0

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);

Comments

0

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]);
})

Comments

0

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);

Comments

0

<!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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.