簡體   English   中英

如何使用 replace() 方法更改 Javascript 中字符串的所有字符?

[英]How to change all characters of a string in Javascript with replace() method?

我正在嘗試使用 for 循環更改字符串的字符。 我的目標是用下面的字符來改變每個字符。 例如a應轉換為bb應轉換為c ,最后z應轉換為a等。我編寫了以下代碼,但它不起作用。

 function LetterChanges(str) { var char = "abcdefghijklmnoprstuvyz"; for(var i = 0; i < char.length; i++) { var newStr = str.replace(/char[i]/gi, char[i + 1]); // the problem is here } return newStr; } // keep this function call here console.log(LetterChanges(readline()));

您可以找到一個字母並替換為 function。

 function LetterChanges(str) { var char = "abcdefghijklmnoprstuvyz"; return str.replace(/[az]/gi, c => char[char.indexOf(c) + 1] || char[0]); } console.log(LetterChanges('foobar'));

在一行中:

const LetterChanges = (str=‘’) => String.fromCharCode(...[...str].map(c => c.charCodeAt(0) +1));

或者,如果您願意:

function LetterChanges(str = ‘’) {
    return String.fromCharCode(...[...str].map(c => c.charCodeAt(0) +1));
}

暫無
暫無

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

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