I wrote a function that solves the problem exactly.
The first argument is the string to be parameterized. You should put your variables on this line, for example, in the format "% s1,% s2, ...% s12" .
Other arguments are parameters respectively for this line.
const parameterizedString = (...args) => { const str = args[0]; const params = args.filter((arg, index) => index !== 0); if (!str) return ""; return str.replace(/%s[0-9]+/g, matchedStr => { const variableIndex = matchedStr.replace("%s", "") - 1; return params[variableIndex]; }); }
Examples
parameterizedString("my name is %s1 and surname is %s2", "John", "Doe"); // returns "my name is John and surname is Doe" parameterizedString("this%s1 %s2 %s3", " method", "sooo", "goood"); // returns "this method sooo goood"
If the variable position changes on this line, this function also supports it without changing the parameters of the function.
parameterizedString("i have %s2 %s1 and %s4 %s3.", "books", 5, "pencils", "6"); // returns "i have 5 books and 6 pencils."
fatihturgut Jul 09 '19 at 17:41 2019-07-09 17:41
source share