I am trying to use javascript to dynamically replace content inside curly braces. Here is an example of my code:
var myString = "This is {name} {type} {type} in {Java}} Yes, a {type}!"; Var changed alarre = ['name', 'adjective', 'type']; Var replacewith = ['John', 'simple', 'string']; (MyString.replace (/ \ {replaceArray [i] \} / gi, replacewith [i]);} Alert (MyString) (Var i = 0; i & lt; = replaceArray.length - 1; i ++) ); The above code, should, output "This is a simple string of javascript in javascript! Yes, a string!".
Here's what:
- We are given a string which needs value in the braces
- Using a loop "replacement array" to find all the values in curly braces Goes to
-
However, I have no luck, especially since One value can be changed in many places , and that I am working as a dynamic value within regular expressions.
First of all, String.replace is not destructive - it does not change the string itself, therefore You have to set myString = myString.replace (...) . Second, you can dynamically create RegExp objects new RegExp , so the result of all will be: var myString = "This Replace [array], replacement array = ['name', 'adjective', 'type'], replace = ['john', ' Simple ',' string ']; (Var i = 0; i & lt; replaceArray.length; i ++) {myString = myString.replace (new RegExp ('{' + replaceArray [i] + '}', 'gi'), replacement [i] ); }
Comments
Post a Comment