How to replace words in a sentence with its values in javascript?












1















I have the following scenerio , where I have the following string



Edit:  const message = results.doc.data().taskSettings.taskInProgressSettings.pushNotifications.onAssignmentNotifyEmployee.message;


I get the message from db , and the variables are not necessarily taskId , customerName . It can be taskId , customerName , customerId, taskCreaterName , employeeName , employeeId. The message may contain any of the above variables and i need to replace them in run time with its values.



message:`Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}`
let taskId = T-100;
let taskCreaterName = 'mark';
let customerName = 'henry';


and I want to replace the variables (taskId , taskCreaterName , customername) with its values and the final result should be the following,



newMessage = Task T-100 assigned by mark for customer henry


What would be the best way of achieving this. Thanks










share|improve this question

























  • What's the problem you are facing? Just place message line at bottom

    – Sagar
    Nov 14 '18 at 11:03











  • when you say let taskId = T-100; do you want the literal string T-100 to be parsed into the string, or you want the expression result T minus 100?

    – Ahmad
    Nov 14 '18 at 11:03











  • like this ? codepen.io/anon/pen/yQMzGJ

    – Mars.Tsai
    Nov 14 '18 at 11:04











  • @Sagar The message is dynamic from db and Iam not able to replace the variables with its values in run time.

    – Shaik Nizamuddin
    Nov 14 '18 at 11:05











  • @ShaikNizamuddin codepen.io/anon/pen/yQMzGJ

    – Sagar
    Nov 14 '18 at 11:07


















1















I have the following scenerio , where I have the following string



Edit:  const message = results.doc.data().taskSettings.taskInProgressSettings.pushNotifications.onAssignmentNotifyEmployee.message;


I get the message from db , and the variables are not necessarily taskId , customerName . It can be taskId , customerName , customerId, taskCreaterName , employeeName , employeeId. The message may contain any of the above variables and i need to replace them in run time with its values.



message:`Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}`
let taskId = T-100;
let taskCreaterName = 'mark';
let customerName = 'henry';


and I want to replace the variables (taskId , taskCreaterName , customername) with its values and the final result should be the following,



newMessage = Task T-100 assigned by mark for customer henry


What would be the best way of achieving this. Thanks










share|improve this question

























  • What's the problem you are facing? Just place message line at bottom

    – Sagar
    Nov 14 '18 at 11:03











  • when you say let taskId = T-100; do you want the literal string T-100 to be parsed into the string, or you want the expression result T minus 100?

    – Ahmad
    Nov 14 '18 at 11:03











  • like this ? codepen.io/anon/pen/yQMzGJ

    – Mars.Tsai
    Nov 14 '18 at 11:04











  • @Sagar The message is dynamic from db and Iam not able to replace the variables with its values in run time.

    – Shaik Nizamuddin
    Nov 14 '18 at 11:05











  • @ShaikNizamuddin codepen.io/anon/pen/yQMzGJ

    – Sagar
    Nov 14 '18 at 11:07
















1












1








1








I have the following scenerio , where I have the following string



Edit:  const message = results.doc.data().taskSettings.taskInProgressSettings.pushNotifications.onAssignmentNotifyEmployee.message;


I get the message from db , and the variables are not necessarily taskId , customerName . It can be taskId , customerName , customerId, taskCreaterName , employeeName , employeeId. The message may contain any of the above variables and i need to replace them in run time with its values.



message:`Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}`
let taskId = T-100;
let taskCreaterName = 'mark';
let customerName = 'henry';


and I want to replace the variables (taskId , taskCreaterName , customername) with its values and the final result should be the following,



newMessage = Task T-100 assigned by mark for customer henry


What would be the best way of achieving this. Thanks










share|improve this question
















I have the following scenerio , where I have the following string



Edit:  const message = results.doc.data().taskSettings.taskInProgressSettings.pushNotifications.onAssignmentNotifyEmployee.message;


I get the message from db , and the variables are not necessarily taskId , customerName . It can be taskId , customerName , customerId, taskCreaterName , employeeName , employeeId. The message may contain any of the above variables and i need to replace them in run time with its values.



message:`Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}`
let taskId = T-100;
let taskCreaterName = 'mark';
let customerName = 'henry';


and I want to replace the variables (taskId , taskCreaterName , customername) with its values and the final result should be the following,



newMessage = Task T-100 assigned by mark for customer henry


What would be the best way of achieving this. Thanks







javascript string typescript replace






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 11:15







Shaik Nizamuddin

















asked Nov 14 '18 at 11:00









Shaik NizamuddinShaik Nizamuddin

10211




10211













  • What's the problem you are facing? Just place message line at bottom

    – Sagar
    Nov 14 '18 at 11:03











  • when you say let taskId = T-100; do you want the literal string T-100 to be parsed into the string, or you want the expression result T minus 100?

    – Ahmad
    Nov 14 '18 at 11:03











  • like this ? codepen.io/anon/pen/yQMzGJ

    – Mars.Tsai
    Nov 14 '18 at 11:04











  • @Sagar The message is dynamic from db and Iam not able to replace the variables with its values in run time.

    – Shaik Nizamuddin
    Nov 14 '18 at 11:05











  • @ShaikNizamuddin codepen.io/anon/pen/yQMzGJ

    – Sagar
    Nov 14 '18 at 11:07





















  • What's the problem you are facing? Just place message line at bottom

    – Sagar
    Nov 14 '18 at 11:03











  • when you say let taskId = T-100; do you want the literal string T-100 to be parsed into the string, or you want the expression result T minus 100?

    – Ahmad
    Nov 14 '18 at 11:03











  • like this ? codepen.io/anon/pen/yQMzGJ

    – Mars.Tsai
    Nov 14 '18 at 11:04











  • @Sagar The message is dynamic from db and Iam not able to replace the variables with its values in run time.

    – Shaik Nizamuddin
    Nov 14 '18 at 11:05











  • @ShaikNizamuddin codepen.io/anon/pen/yQMzGJ

    – Sagar
    Nov 14 '18 at 11:07



















What's the problem you are facing? Just place message line at bottom

– Sagar
Nov 14 '18 at 11:03





What's the problem you are facing? Just place message line at bottom

– Sagar
Nov 14 '18 at 11:03













when you say let taskId = T-100; do you want the literal string T-100 to be parsed into the string, or you want the expression result T minus 100?

– Ahmad
Nov 14 '18 at 11:03





when you say let taskId = T-100; do you want the literal string T-100 to be parsed into the string, or you want the expression result T minus 100?

– Ahmad
Nov 14 '18 at 11:03













like this ? codepen.io/anon/pen/yQMzGJ

– Mars.Tsai
Nov 14 '18 at 11:04





like this ? codepen.io/anon/pen/yQMzGJ

– Mars.Tsai
Nov 14 '18 at 11:04













@Sagar The message is dynamic from db and Iam not able to replace the variables with its values in run time.

– Shaik Nizamuddin
Nov 14 '18 at 11:05





@Sagar The message is dynamic from db and Iam not able to replace the variables with its values in run time.

– Shaik Nizamuddin
Nov 14 '18 at 11:05













@ShaikNizamuddin codepen.io/anon/pen/yQMzGJ

– Sagar
Nov 14 '18 at 11:07







@ShaikNizamuddin codepen.io/anon/pen/yQMzGJ

– Sagar
Nov 14 '18 at 11:07














6 Answers
6






active

oldest

votes


















1














To make this work in generic way you can keep 1 object (like 'withData' I created below, rather than maintaining different variables) to store values to replace and let generic function (replace) take care of all the changes like below






let message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}'

let withData = {
taskId: 'T-100'
, taskCreaterName: 'mark'
, customerName: 'henry'
}

function replace(obj, withData) {
let result = message.slice(0)
for (let [key, value] of Object.entries(withData)) {
result = result.replace('${' + key + '}', value)
}

return result
}

let result = replace(message, withData)

console.log(result)

// In case Object.entries is not supported
function replace(obj, withData) {
let result = message.slice(0)
for (let key in withData) {
let value = withData[key]
result = result.replace('${' + key + '}', value)
}

return result
}








share|improve this answer


























  • Iam getting the following error : Property 'entries' does not exist on type 'ObjectConstructor'

    – Shaik Nizamuddin
    Nov 14 '18 at 11:25











  • Okay. Which browser are you using?

    – Nitish Narang
    Nov 14 '18 at 11:26











  • chrome browser and its firebase

    – Shaik Nizamuddin
    Nov 14 '18 at 11:27











  • No problem, may be your chrome needs update. Never mind updated my answer and you can now use it without "object.entries". pls check

    – Nitish Narang
    Nov 14 '18 at 11:29






  • 1





    Sir , Iam working on it ,and definitely I will update you. thanks

    – Shaik Nizamuddin
    Nov 14 '18 at 11:49



















1














You can store values with target names in object and use .replace() to replacing target part of string with values in object. If value with matched name exist in object replace it with value.






var message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName} and ${newVar}';
var values = {
taskId: 'T-100',
taskCreaterName: 'mark',
customerName: 'henry'
};
var newStr = message.replace(/${(w+)}/g, function(match, cont){
return typeof values[cont] !== 'undefined' ? values[cont] : match;
})
console.log(newStr);








share|improve this answer


























  • @ShaikNizamuddin i think this is what you want

    – Mohammad
    Nov 14 '18 at 11:41



















0














You don't need to do anything. Js will replace the variables with value at runtime.






share|improve this answer



















  • 1





    need to check on the support for that developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…, for instance this will not work in IE

    – Quince
    Nov 14 '18 at 11:06













  • When i see logs before and after , I get the same sentence with no changes

    – Shaik Nizamuddin
    Nov 14 '18 at 11:07



















0














This is probably the simplest way to accomplish the thing you're looking for:



let taskId = 'T-100';
let taskCreaterName = 'mark';
let customerName = 'henry';

let newMessage = 'Task ' + taskId + ' assigned by ' + taskCreaterName + ' for customer ' + customerName;


Where newMessage has "Task T-100 assigned by mark for customer henry".






share|improve this answer



















  • 1





    OP mentioned that message comes from db and is dynamic

    – barbsan
    Nov 14 '18 at 11:11











  • Well, OP edited the question after I posted my answer. I answered his original question just fine.

    – Steven McConnon
    Nov 14 '18 at 11:51











  • It was in comment before you answered

    – barbsan
    Nov 14 '18 at 11:52



















0














Depending on the value of T in your code, which you did not provide, I will assume it holds a valid Integer number.






let T = parseInt(Math.random() * 1000);

let taskId = T-100;
let taskCreaterName = 'mark';
let customerName = 'henry';

//assuming T-100 is a result of an expression, you would do something like:
console.log(`Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}`);

//assming T-100 is a litral string, then you don't need to parse it at all
console.log(`Task T-100 assigned by ${taskCreaterName} for customer ${customerName}`);








share|improve this answer































    0














    You could use String#replace with custom callback and eval (name contains only chars [a-zA-z0-9] so it should be safe)






    var message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}';
    let taskId = 'T-100';
    let taskCreaterName = 'mark';
    let customerName = 'henry';

    var newMessage = message.replace(/${([w]+)}/g, function(match, name){
    return eval(name);
    })

    console.log(newMessage);








    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53298650%2fhow-to-replace-words-in-a-sentence-with-its-values-in-javascript%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      6 Answers
      6






      active

      oldest

      votes








      6 Answers
      6






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      To make this work in generic way you can keep 1 object (like 'withData' I created below, rather than maintaining different variables) to store values to replace and let generic function (replace) take care of all the changes like below






      let message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}'

      let withData = {
      taskId: 'T-100'
      , taskCreaterName: 'mark'
      , customerName: 'henry'
      }

      function replace(obj, withData) {
      let result = message.slice(0)
      for (let [key, value] of Object.entries(withData)) {
      result = result.replace('${' + key + '}', value)
      }

      return result
      }

      let result = replace(message, withData)

      console.log(result)

      // In case Object.entries is not supported
      function replace(obj, withData) {
      let result = message.slice(0)
      for (let key in withData) {
      let value = withData[key]
      result = result.replace('${' + key + '}', value)
      }

      return result
      }








      share|improve this answer


























      • Iam getting the following error : Property 'entries' does not exist on type 'ObjectConstructor'

        – Shaik Nizamuddin
        Nov 14 '18 at 11:25











      • Okay. Which browser are you using?

        – Nitish Narang
        Nov 14 '18 at 11:26











      • chrome browser and its firebase

        – Shaik Nizamuddin
        Nov 14 '18 at 11:27











      • No problem, may be your chrome needs update. Never mind updated my answer and you can now use it without "object.entries". pls check

        – Nitish Narang
        Nov 14 '18 at 11:29






      • 1





        Sir , Iam working on it ,and definitely I will update you. thanks

        – Shaik Nizamuddin
        Nov 14 '18 at 11:49
















      1














      To make this work in generic way you can keep 1 object (like 'withData' I created below, rather than maintaining different variables) to store values to replace and let generic function (replace) take care of all the changes like below






      let message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}'

      let withData = {
      taskId: 'T-100'
      , taskCreaterName: 'mark'
      , customerName: 'henry'
      }

      function replace(obj, withData) {
      let result = message.slice(0)
      for (let [key, value] of Object.entries(withData)) {
      result = result.replace('${' + key + '}', value)
      }

      return result
      }

      let result = replace(message, withData)

      console.log(result)

      // In case Object.entries is not supported
      function replace(obj, withData) {
      let result = message.slice(0)
      for (let key in withData) {
      let value = withData[key]
      result = result.replace('${' + key + '}', value)
      }

      return result
      }








      share|improve this answer


























      • Iam getting the following error : Property 'entries' does not exist on type 'ObjectConstructor'

        – Shaik Nizamuddin
        Nov 14 '18 at 11:25











      • Okay. Which browser are you using?

        – Nitish Narang
        Nov 14 '18 at 11:26











      • chrome browser and its firebase

        – Shaik Nizamuddin
        Nov 14 '18 at 11:27











      • No problem, may be your chrome needs update. Never mind updated my answer and you can now use it without "object.entries". pls check

        – Nitish Narang
        Nov 14 '18 at 11:29






      • 1





        Sir , Iam working on it ,and definitely I will update you. thanks

        – Shaik Nizamuddin
        Nov 14 '18 at 11:49














      1












      1








      1







      To make this work in generic way you can keep 1 object (like 'withData' I created below, rather than maintaining different variables) to store values to replace and let generic function (replace) take care of all the changes like below






      let message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}'

      let withData = {
      taskId: 'T-100'
      , taskCreaterName: 'mark'
      , customerName: 'henry'
      }

      function replace(obj, withData) {
      let result = message.slice(0)
      for (let [key, value] of Object.entries(withData)) {
      result = result.replace('${' + key + '}', value)
      }

      return result
      }

      let result = replace(message, withData)

      console.log(result)

      // In case Object.entries is not supported
      function replace(obj, withData) {
      let result = message.slice(0)
      for (let key in withData) {
      let value = withData[key]
      result = result.replace('${' + key + '}', value)
      }

      return result
      }








      share|improve this answer















      To make this work in generic way you can keep 1 object (like 'withData' I created below, rather than maintaining different variables) to store values to replace and let generic function (replace) take care of all the changes like below






      let message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}'

      let withData = {
      taskId: 'T-100'
      , taskCreaterName: 'mark'
      , customerName: 'henry'
      }

      function replace(obj, withData) {
      let result = message.slice(0)
      for (let [key, value] of Object.entries(withData)) {
      result = result.replace('${' + key + '}', value)
      }

      return result
      }

      let result = replace(message, withData)

      console.log(result)

      // In case Object.entries is not supported
      function replace(obj, withData) {
      let result = message.slice(0)
      for (let key in withData) {
      let value = withData[key]
      result = result.replace('${' + key + '}', value)
      }

      return result
      }








      let message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}'

      let withData = {
      taskId: 'T-100'
      , taskCreaterName: 'mark'
      , customerName: 'henry'
      }

      function replace(obj, withData) {
      let result = message.slice(0)
      for (let [key, value] of Object.entries(withData)) {
      result = result.replace('${' + key + '}', value)
      }

      return result
      }

      let result = replace(message, withData)

      console.log(result)

      // In case Object.entries is not supported
      function replace(obj, withData) {
      let result = message.slice(0)
      for (let key in withData) {
      let value = withData[key]
      result = result.replace('${' + key + '}', value)
      }

      return result
      }





      let message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}'

      let withData = {
      taskId: 'T-100'
      , taskCreaterName: 'mark'
      , customerName: 'henry'
      }

      function replace(obj, withData) {
      let result = message.slice(0)
      for (let [key, value] of Object.entries(withData)) {
      result = result.replace('${' + key + '}', value)
      }

      return result
      }

      let result = replace(message, withData)

      console.log(result)

      // In case Object.entries is not supported
      function replace(obj, withData) {
      let result = message.slice(0)
      for (let key in withData) {
      let value = withData[key]
      result = result.replace('${' + key + '}', value)
      }

      return result
      }






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 14 '18 at 11:28

























      answered Nov 14 '18 at 11:11









      Nitish NarangNitish Narang

      2,9401815




      2,9401815













      • Iam getting the following error : Property 'entries' does not exist on type 'ObjectConstructor'

        – Shaik Nizamuddin
        Nov 14 '18 at 11:25











      • Okay. Which browser are you using?

        – Nitish Narang
        Nov 14 '18 at 11:26











      • chrome browser and its firebase

        – Shaik Nizamuddin
        Nov 14 '18 at 11:27











      • No problem, may be your chrome needs update. Never mind updated my answer and you can now use it without "object.entries". pls check

        – Nitish Narang
        Nov 14 '18 at 11:29






      • 1





        Sir , Iam working on it ,and definitely I will update you. thanks

        – Shaik Nizamuddin
        Nov 14 '18 at 11:49



















      • Iam getting the following error : Property 'entries' does not exist on type 'ObjectConstructor'

        – Shaik Nizamuddin
        Nov 14 '18 at 11:25











      • Okay. Which browser are you using?

        – Nitish Narang
        Nov 14 '18 at 11:26











      • chrome browser and its firebase

        – Shaik Nizamuddin
        Nov 14 '18 at 11:27











      • No problem, may be your chrome needs update. Never mind updated my answer and you can now use it without "object.entries". pls check

        – Nitish Narang
        Nov 14 '18 at 11:29






      • 1





        Sir , Iam working on it ,and definitely I will update you. thanks

        – Shaik Nizamuddin
        Nov 14 '18 at 11:49

















      Iam getting the following error : Property 'entries' does not exist on type 'ObjectConstructor'

      – Shaik Nizamuddin
      Nov 14 '18 at 11:25





      Iam getting the following error : Property 'entries' does not exist on type 'ObjectConstructor'

      – Shaik Nizamuddin
      Nov 14 '18 at 11:25













      Okay. Which browser are you using?

      – Nitish Narang
      Nov 14 '18 at 11:26





      Okay. Which browser are you using?

      – Nitish Narang
      Nov 14 '18 at 11:26













      chrome browser and its firebase

      – Shaik Nizamuddin
      Nov 14 '18 at 11:27





      chrome browser and its firebase

      – Shaik Nizamuddin
      Nov 14 '18 at 11:27













      No problem, may be your chrome needs update. Never mind updated my answer and you can now use it without "object.entries". pls check

      – Nitish Narang
      Nov 14 '18 at 11:29





      No problem, may be your chrome needs update. Never mind updated my answer and you can now use it without "object.entries". pls check

      – Nitish Narang
      Nov 14 '18 at 11:29




      1




      1





      Sir , Iam working on it ,and definitely I will update you. thanks

      – Shaik Nizamuddin
      Nov 14 '18 at 11:49





      Sir , Iam working on it ,and definitely I will update you. thanks

      – Shaik Nizamuddin
      Nov 14 '18 at 11:49













      1














      You can store values with target names in object and use .replace() to replacing target part of string with values in object. If value with matched name exist in object replace it with value.






      var message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName} and ${newVar}';
      var values = {
      taskId: 'T-100',
      taskCreaterName: 'mark',
      customerName: 'henry'
      };
      var newStr = message.replace(/${(w+)}/g, function(match, cont){
      return typeof values[cont] !== 'undefined' ? values[cont] : match;
      })
      console.log(newStr);








      share|improve this answer


























      • @ShaikNizamuddin i think this is what you want

        – Mohammad
        Nov 14 '18 at 11:41
















      1














      You can store values with target names in object and use .replace() to replacing target part of string with values in object. If value with matched name exist in object replace it with value.






      var message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName} and ${newVar}';
      var values = {
      taskId: 'T-100',
      taskCreaterName: 'mark',
      customerName: 'henry'
      };
      var newStr = message.replace(/${(w+)}/g, function(match, cont){
      return typeof values[cont] !== 'undefined' ? values[cont] : match;
      })
      console.log(newStr);








      share|improve this answer


























      • @ShaikNizamuddin i think this is what you want

        – Mohammad
        Nov 14 '18 at 11:41














      1












      1








      1







      You can store values with target names in object and use .replace() to replacing target part of string with values in object. If value with matched name exist in object replace it with value.






      var message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName} and ${newVar}';
      var values = {
      taskId: 'T-100',
      taskCreaterName: 'mark',
      customerName: 'henry'
      };
      var newStr = message.replace(/${(w+)}/g, function(match, cont){
      return typeof values[cont] !== 'undefined' ? values[cont] : match;
      })
      console.log(newStr);








      share|improve this answer















      You can store values with target names in object and use .replace() to replacing target part of string with values in object. If value with matched name exist in object replace it with value.






      var message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName} and ${newVar}';
      var values = {
      taskId: 'T-100',
      taskCreaterName: 'mark',
      customerName: 'henry'
      };
      var newStr = message.replace(/${(w+)}/g, function(match, cont){
      return typeof values[cont] !== 'undefined' ? values[cont] : match;
      })
      console.log(newStr);








      var message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName} and ${newVar}';
      var values = {
      taskId: 'T-100',
      taskCreaterName: 'mark',
      customerName: 'henry'
      };
      var newStr = message.replace(/${(w+)}/g, function(match, cont){
      return typeof values[cont] !== 'undefined' ? values[cont] : match;
      })
      console.log(newStr);





      var message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName} and ${newVar}';
      var values = {
      taskId: 'T-100',
      taskCreaterName: 'mark',
      customerName: 'henry'
      };
      var newStr = message.replace(/${(w+)}/g, function(match, cont){
      return typeof values[cont] !== 'undefined' ? values[cont] : match;
      })
      console.log(newStr);






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 14 '18 at 11:39

























      answered Nov 14 '18 at 11:06









      MohammadMohammad

      15.6k123461




      15.6k123461













      • @ShaikNizamuddin i think this is what you want

        – Mohammad
        Nov 14 '18 at 11:41



















      • @ShaikNizamuddin i think this is what you want

        – Mohammad
        Nov 14 '18 at 11:41

















      @ShaikNizamuddin i think this is what you want

      – Mohammad
      Nov 14 '18 at 11:41





      @ShaikNizamuddin i think this is what you want

      – Mohammad
      Nov 14 '18 at 11:41











      0














      You don't need to do anything. Js will replace the variables with value at runtime.






      share|improve this answer



















      • 1





        need to check on the support for that developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…, for instance this will not work in IE

        – Quince
        Nov 14 '18 at 11:06













      • When i see logs before and after , I get the same sentence with no changes

        – Shaik Nizamuddin
        Nov 14 '18 at 11:07
















      0














      You don't need to do anything. Js will replace the variables with value at runtime.






      share|improve this answer



















      • 1





        need to check on the support for that developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…, for instance this will not work in IE

        – Quince
        Nov 14 '18 at 11:06













      • When i see logs before and after , I get the same sentence with no changes

        – Shaik Nizamuddin
        Nov 14 '18 at 11:07














      0












      0








      0







      You don't need to do anything. Js will replace the variables with value at runtime.






      share|improve this answer













      You don't need to do anything. Js will replace the variables with value at runtime.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Nov 14 '18 at 11:04









      Hari PrathapHari Prathap

      705




      705








      • 1





        need to check on the support for that developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…, for instance this will not work in IE

        – Quince
        Nov 14 '18 at 11:06













      • When i see logs before and after , I get the same sentence with no changes

        – Shaik Nizamuddin
        Nov 14 '18 at 11:07














      • 1





        need to check on the support for that developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…, for instance this will not work in IE

        – Quince
        Nov 14 '18 at 11:06













      • When i see logs before and after , I get the same sentence with no changes

        – Shaik Nizamuddin
        Nov 14 '18 at 11:07








      1




      1





      need to check on the support for that developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…, for instance this will not work in IE

      – Quince
      Nov 14 '18 at 11:06







      need to check on the support for that developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…, for instance this will not work in IE

      – Quince
      Nov 14 '18 at 11:06















      When i see logs before and after , I get the same sentence with no changes

      – Shaik Nizamuddin
      Nov 14 '18 at 11:07





      When i see logs before and after , I get the same sentence with no changes

      – Shaik Nizamuddin
      Nov 14 '18 at 11:07











      0














      This is probably the simplest way to accomplish the thing you're looking for:



      let taskId = 'T-100';
      let taskCreaterName = 'mark';
      let customerName = 'henry';

      let newMessage = 'Task ' + taskId + ' assigned by ' + taskCreaterName + ' for customer ' + customerName;


      Where newMessage has "Task T-100 assigned by mark for customer henry".






      share|improve this answer



















      • 1





        OP mentioned that message comes from db and is dynamic

        – barbsan
        Nov 14 '18 at 11:11











      • Well, OP edited the question after I posted my answer. I answered his original question just fine.

        – Steven McConnon
        Nov 14 '18 at 11:51











      • It was in comment before you answered

        – barbsan
        Nov 14 '18 at 11:52
















      0














      This is probably the simplest way to accomplish the thing you're looking for:



      let taskId = 'T-100';
      let taskCreaterName = 'mark';
      let customerName = 'henry';

      let newMessage = 'Task ' + taskId + ' assigned by ' + taskCreaterName + ' for customer ' + customerName;


      Where newMessage has "Task T-100 assigned by mark for customer henry".






      share|improve this answer



















      • 1





        OP mentioned that message comes from db and is dynamic

        – barbsan
        Nov 14 '18 at 11:11











      • Well, OP edited the question after I posted my answer. I answered his original question just fine.

        – Steven McConnon
        Nov 14 '18 at 11:51











      • It was in comment before you answered

        – barbsan
        Nov 14 '18 at 11:52














      0












      0








      0







      This is probably the simplest way to accomplish the thing you're looking for:



      let taskId = 'T-100';
      let taskCreaterName = 'mark';
      let customerName = 'henry';

      let newMessage = 'Task ' + taskId + ' assigned by ' + taskCreaterName + ' for customer ' + customerName;


      Where newMessage has "Task T-100 assigned by mark for customer henry".






      share|improve this answer













      This is probably the simplest way to accomplish the thing you're looking for:



      let taskId = 'T-100';
      let taskCreaterName = 'mark';
      let customerName = 'henry';

      let newMessage = 'Task ' + taskId + ' assigned by ' + taskCreaterName + ' for customer ' + customerName;


      Where newMessage has "Task T-100 assigned by mark for customer henry".







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Nov 14 '18 at 11:07









      Steven McConnonSteven McConnon

      1,100817




      1,100817








      • 1





        OP mentioned that message comes from db and is dynamic

        – barbsan
        Nov 14 '18 at 11:11











      • Well, OP edited the question after I posted my answer. I answered his original question just fine.

        – Steven McConnon
        Nov 14 '18 at 11:51











      • It was in comment before you answered

        – barbsan
        Nov 14 '18 at 11:52














      • 1





        OP mentioned that message comes from db and is dynamic

        – barbsan
        Nov 14 '18 at 11:11











      • Well, OP edited the question after I posted my answer. I answered his original question just fine.

        – Steven McConnon
        Nov 14 '18 at 11:51











      • It was in comment before you answered

        – barbsan
        Nov 14 '18 at 11:52








      1




      1





      OP mentioned that message comes from db and is dynamic

      – barbsan
      Nov 14 '18 at 11:11





      OP mentioned that message comes from db and is dynamic

      – barbsan
      Nov 14 '18 at 11:11













      Well, OP edited the question after I posted my answer. I answered his original question just fine.

      – Steven McConnon
      Nov 14 '18 at 11:51





      Well, OP edited the question after I posted my answer. I answered his original question just fine.

      – Steven McConnon
      Nov 14 '18 at 11:51













      It was in comment before you answered

      – barbsan
      Nov 14 '18 at 11:52





      It was in comment before you answered

      – barbsan
      Nov 14 '18 at 11:52











      0














      Depending on the value of T in your code, which you did not provide, I will assume it holds a valid Integer number.






      let T = parseInt(Math.random() * 1000);

      let taskId = T-100;
      let taskCreaterName = 'mark';
      let customerName = 'henry';

      //assuming T-100 is a result of an expression, you would do something like:
      console.log(`Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}`);

      //assming T-100 is a litral string, then you don't need to parse it at all
      console.log(`Task T-100 assigned by ${taskCreaterName} for customer ${customerName}`);








      share|improve this answer




























        0














        Depending on the value of T in your code, which you did not provide, I will assume it holds a valid Integer number.






        let T = parseInt(Math.random() * 1000);

        let taskId = T-100;
        let taskCreaterName = 'mark';
        let customerName = 'henry';

        //assuming T-100 is a result of an expression, you would do something like:
        console.log(`Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}`);

        //assming T-100 is a litral string, then you don't need to parse it at all
        console.log(`Task T-100 assigned by ${taskCreaterName} for customer ${customerName}`);








        share|improve this answer


























          0












          0








          0







          Depending on the value of T in your code, which you did not provide, I will assume it holds a valid Integer number.






          let T = parseInt(Math.random() * 1000);

          let taskId = T-100;
          let taskCreaterName = 'mark';
          let customerName = 'henry';

          //assuming T-100 is a result of an expression, you would do something like:
          console.log(`Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}`);

          //assming T-100 is a litral string, then you don't need to parse it at all
          console.log(`Task T-100 assigned by ${taskCreaterName} for customer ${customerName}`);








          share|improve this answer













          Depending on the value of T in your code, which you did not provide, I will assume it holds a valid Integer number.






          let T = parseInt(Math.random() * 1000);

          let taskId = T-100;
          let taskCreaterName = 'mark';
          let customerName = 'henry';

          //assuming T-100 is a result of an expression, you would do something like:
          console.log(`Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}`);

          //assming T-100 is a litral string, then you don't need to parse it at all
          console.log(`Task T-100 assigned by ${taskCreaterName} for customer ${customerName}`);








          let T = parseInt(Math.random() * 1000);

          let taskId = T-100;
          let taskCreaterName = 'mark';
          let customerName = 'henry';

          //assuming T-100 is a result of an expression, you would do something like:
          console.log(`Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}`);

          //assming T-100 is a litral string, then you don't need to parse it at all
          console.log(`Task T-100 assigned by ${taskCreaterName} for customer ${customerName}`);





          let T = parseInt(Math.random() * 1000);

          let taskId = T-100;
          let taskCreaterName = 'mark';
          let customerName = 'henry';

          //assuming T-100 is a result of an expression, you would do something like:
          console.log(`Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}`);

          //assming T-100 is a litral string, then you don't need to parse it at all
          console.log(`Task T-100 assigned by ${taskCreaterName} for customer ${customerName}`);






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 14 '18 at 11:07









          AhmadAhmad

          8,23543563




          8,23543563























              0














              You could use String#replace with custom callback and eval (name contains only chars [a-zA-z0-9] so it should be safe)






              var message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}';
              let taskId = 'T-100';
              let taskCreaterName = 'mark';
              let customerName = 'henry';

              var newMessage = message.replace(/${([w]+)}/g, function(match, name){
              return eval(name);
              })

              console.log(newMessage);








              share|improve this answer




























                0














                You could use String#replace with custom callback and eval (name contains only chars [a-zA-z0-9] so it should be safe)






                var message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}';
                let taskId = 'T-100';
                let taskCreaterName = 'mark';
                let customerName = 'henry';

                var newMessage = message.replace(/${([w]+)}/g, function(match, name){
                return eval(name);
                })

                console.log(newMessage);








                share|improve this answer


























                  0












                  0








                  0







                  You could use String#replace with custom callback and eval (name contains only chars [a-zA-z0-9] so it should be safe)






                  var message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}';
                  let taskId = 'T-100';
                  let taskCreaterName = 'mark';
                  let customerName = 'henry';

                  var newMessage = message.replace(/${([w]+)}/g, function(match, name){
                  return eval(name);
                  })

                  console.log(newMessage);








                  share|improve this answer













                  You could use String#replace with custom callback and eval (name contains only chars [a-zA-z0-9] so it should be safe)






                  var message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}';
                  let taskId = 'T-100';
                  let taskCreaterName = 'mark';
                  let customerName = 'henry';

                  var newMessage = message.replace(/${([w]+)}/g, function(match, name){
                  return eval(name);
                  })

                  console.log(newMessage);








                  var message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}';
                  let taskId = 'T-100';
                  let taskCreaterName = 'mark';
                  let customerName = 'henry';

                  var newMessage = message.replace(/${([w]+)}/g, function(match, name){
                  return eval(name);
                  })

                  console.log(newMessage);





                  var message = 'Task ${taskId} assigned by ${taskCreaterName} for customer ${customerName}';
                  let taskId = 'T-100';
                  let taskCreaterName = 'mark';
                  let customerName = 'henry';

                  var newMessage = message.replace(/${([w]+)}/g, function(match, name){
                  return eval(name);
                  })

                  console.log(newMessage);






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 14 '18 at 11:28









                  barbsanbarbsan

                  2,41321222




                  2,41321222






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53298650%2fhow-to-replace-words-in-a-sentence-with-its-values-in-javascript%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Bressuire

                      Vorschmack

                      Quarantine