mvaldetaro
mvaldetaro

Reputation: 172

How to replace elements of a string based on the values of an array?

String has already been defined as follows:

const desc = `This is the password you use to access the $0 application. It is not the password for the $1 card. \n With the password, we can only read your statement. No other operations can be performed.`;

Array has already been defined as follows:

const params = ['American', 'American Black'];

I would like to replace:

$0 => American,
$1 => American Black

Expected outcome:

This is the password you use to access the American application. It is not the password for the American Black card. \n With the password, we can only read your statement. No other operations can be performed.

Upvotes: 0

Views: 120

Answers (4)

Pipe
Pipe

Reputation: 2424

If you want to make it work for N parameters, you can do:

const desc = `This is the password you use to access the $0 application. It is not the password for the $1 card. \n With the password, we can only read your statement. No other operations can be performed. Added $2 value, Added $3 value`;
const params = ['American', 'American Black', 'test1', 'test2'];

const result = params.reduce((acum, val, index) => acum.replace("$"+index, val), desc);

console.log(result);

Upvotes: 1

biberman
biberman

Reputation: 5767

if you don't want to change the two constants you could simply replace it with:

var newDesc = desc.replace("$0", params[0]).replace("$1", params[1]);

Upvotes: 0

zfj3ub94rf576hc4eegm
zfj3ub94rf576hc4eegm

Reputation: 1273

If you can't edit the string desc then you can replace $0 and $1 as follows:

x = desc.split('$0').join(params[0])
x = x.split('$1').join(params[1])

return x

Upvotes: 0

Endothermic_Dragon
Endothermic_Dragon

Reputation: 1187

Try this:

const params = ['American', 'American Black'];

const desc = `This is the password you use to access the ${params[0]} application. It is not the password for the ${params[1]} card.\nWith the password, we can only read your statement. No other operations can be performed.`;

console.log(desc)

Always be extra cautious when dealing with credit cards and money. Storing such data as a variable on the user-side code is quite dangerous, as it can be read by anyone quite easily.

Upvotes: 0

Related Questions