-3

Question :

var str = "I have a <animal>, a <flower>, and a <car>.";

now the above string I want to replace below with Tiger, Rose and BMW

<animal> , <flower> and <car> 

Please suggest the best approach for this.

I am working on Angular 2 Application with Typescript.

  • Possible duplicate of [How to replace all occurrences of a string in JavaScript?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – Joe Clay Dec 13 '17 at 13:23
  • @JoeClay normal string is ok .. but i am facing issue for or or string. – AmiDeveloper Dec 13 '17 at 13:28

2 Answers2

2

You can use a regex with a replacer function to evaluate each match and return the appropriate replacement.

var str = "I have a <animal>, a <flower>, and a <car>.";

function replace(source : string, replacements : { [name:string]: string }) {
    return str.replace(  new RegExp("<([A-z]*)>", "g"), (m) => {
        return replacements[m.substring(1, m.length -1)];
    });
}

console.log(replace(str, {
    "animal" : "Tiger",
    "flower" : "Rose",
    "car" : "BMW"
}))
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
0

If you are using Typescript you should declare your string according to https://www.typescriptlang.org/docs/handbook/basic-types.html with let str = 'I have a <animal>, a <flower>, and a <car>.'; Note the single quotes which is a recommendation of the Angular Styleguide (enforced e.g. with ng lint in a continuous delivery pipeline).

Instead of replacing with the common javascript replace methods you can substitute the placeholder already in the code:

Screenshot code see the backticks here

Dirk Lammers
  • 756
  • 6
  • 8