最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript - replace words in string with object values - Stack Overflow

programmeradmin6浏览0评论

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 plete it
   }
}

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 plete it
   }
}
Share Improve this question asked Dec 24, 2019 at 12:51 chachachacha 991 silver badge8 bronze badges 3
  • Look at the replace method – Bergi 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...) – Andreas Commented Dec 24, 2019 at 12:57
  • Like this one? How to replace specific parts in string with javascript with values from object – Andreas Commented Dec 24, 2019 at 13:00
Add a ment  | 

6 Answers 6

Reset to default 6

One way would be to use a regular expression like

/#(\w+)/g

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

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

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

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

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

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

  • 1

  • 2

发布评论

评论列表(0)

  1. 暂无评论