![](/img/trans.png)
[英]How to replace all characters in a string using JavaScript for this specific case: replace . by _
[英]How to change all characters of a string in Javascript with replace() method?
我正在嘗試使用 for 循環更改字符串的字符。 我的目標是用下面的字符來改變每個字符。 例如a應轉換為b , b應轉換為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.