0

I have to replace multiple words in a string.

my code is like this

var csku = "{len}";
 var value = 5;
 var finalPrice = "({con}*{len})+{wid}+{fixed_var}+{extra}+{sqft}+{len}";
console.log(finalPrice.replace(csku, value));

Using this code I got this solution

({con}*5)+{wid}+{fixed_var}+{extra}+{sqft}+{len}

but I want this

({con}*5)+{wid}+{fixed_var}+{extra}+{sqft}+5

I google it for replacing multiple words in the string using one call I find this

str.replace(/X|x/g, '');

Here / and g is used for multiple replace and in this format I have to add static word but in my code csku is not fixed so how can I replace all words in one call using variable

mplungjan
  • 134,906
  • 25
  • 152
  • 209
ND17
  • 210
  • 4
  • 21

3 Answers3

1

Using the code from the duplicate to create a Regex object using the variable

var csku = "{len}";
var value = 5;
var finalPrice = "({con}*{len})+{wid}+{fixed_var}+{extra}+{sqft}+{len}";
var re = new RegExp(csku, "g");
console.log(finalPrice.replace(re, value));
mplungjan
  • 134,906
  • 25
  • 152
  • 209
1

use new RegExp(cksu, 'g') to create a regular expression that'll match all cksu.

new RegExp('{len}', 'g') will return /{len}/g meaning all global matches.

so finalPrice.replace(new RegExp(cksu, 'g'), value) will replace all global matches of cksu with value.

var csku = "{len}";
var value = 5;
var finalPrice = "({con}*{len})+{wid}+{fixed_var}+{extra}+{sqft}+{len}";

console.log(finalPrice.replace(new RegExp(csku, 'g'), value));
user3254198
  • 713
  • 6
  • 22
-2

Standart replace function change just first match. You can use this function:

function ReplaceAll(Source, stringToFind, stringToReplace) {
            var temp = Source;
            var index = temp.indexOf(stringToFind);
            while (index != -1) {
                temp = temp.replace(stringToFind, stringToReplace);
                index = temp.indexOf(stringToFind);
            }
            return temp;
        }
himyata
  • 339
  • 1
  • 9