簡體   English   中英

如何根據數組的值替換字符串的元素?

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

字符串已經定義如下:

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.`;

數組已經定義如下:

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

我想更換:

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

預期結果:

這是您用於訪問美國應用程序的密碼。 這不是美國黑卡的密碼。 \n 使用密碼,我們只能閱讀您的聲明。 不能進行其他操作。

如果你想讓它適用於 N 個參數,你可以這樣做:

 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);

嘗試這個:

 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)

在處理信用卡和金錢時要格外小心。 將這些數據作為變量存儲在用戶端代碼中是非常危險的,因為任何人都可以很容易地讀取它。

如果您無法編輯字符串desc則可以替換 $0 和 $1 如下:

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

return x

如果您不想更改這兩個常量,您可以簡單地將其替換為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM