0

I'm building a web application and getting some descriptions from the server. Those strings that I'm getting sometimes include specific characters in them, which should be replaced with proper values. An example of the string looks like this:

let str = 'Every next purchase provides you with additional %@ days 
of bonuses, up to %@ days.'

I need to replace '%@' with proper values. Probably the best way to get those values is an array, since text may have one '%@' or more. I've been thinking about dealing with this through substring method, but I'm not sure if that's the best way.

Example of values may be like [2,5]. Then result should looks like: 'Every next purchase provides you with additional 2 days of bonuses, up to 5 days.'

Thanks for any help.

mantebose
  • 93
  • 1
  • 7
  • Possible duplicate of [Replace multiple strings with multiple other strings](https://stackoverflow.com/questions/15604140/replace-multiple-strings-with-multiple-other-strings) – Heretic Monkey Feb 06 '19 at 14:04
  • @HereticMonkey, not duplicate. In my case the characters that should be replaced are the same all the time. So in my case replace wouldn't work. – mantebose Feb 06 '19 at 14:10
  • You can use the same key function though, just don't include multiple search strings. IOW, `str.replace(/%@/gi, function(matched){`... – Heretic Monkey Feb 06 '19 at 14:12

1 Answers1

0

Use regex and replace method of string to replace character(s )in the string. It returns new string after the process.

let str = 'Every next purchase provides you with additional %@ days'; 
let regex = /%@/gi;
console.log(str.replace(regex, 'yourvalue'));

It depends how you replace it, you can use loop through and replace with array values with same value (not with unique one), again it depends on what you are trying to achieve.

const str = 'Every next purchase provides you with additional %@ days %@';
const array = ['value1', 'value2'];
const count = (str.match(/%@/gi) || []).length;
const regex = /%@/;

let newString;

for (let i = 0; i < count; i++) {
  newString = i === 0 ? str.replace(regex, array[i]) : newString.replace(regex, array[i]);
  alert(newString);
}

Regarding substring(): The method extracts characters from string between two SPECIFIC indices. Since you are getting data from the server, and I believe it's a dynamic data and the indexes of those characters can change, therefore using substring() might not help.

Maihan Nijat
  • 9,054
  • 11
  • 62
  • 110
  • 1
    Your variant will update character with same value in all places. While string may consist of two %@ and values may be [2, 5] for example. – mantebose Feb 06 '19 at 13:59