用字母表中的数字为Javascript短语中的字母指定数字
我想知道如何在Javascript中获取一个数组短语,然后使其输出字母旁边的字母,以显示它们在字母表中的位置,例如计算机输出3C15o13m21u等等。下面的代码中显示了我的短语用字母表中的数字为Javascript短语中的字母指定数字,javascript,arrays,Javascript,Arrays,我想知道如何在Javascript中获取一个数组短语,然后使其输出字母旁边的字母,以显示它们在字母表中的位置,例如计算机输出3C15o13m21u等等。下面的代码中显示了我的短语 var firstPhrase = "Computers are the most fun way to use your time"; alert(firstPhrase); 这应该起作用: var phrase = 'Computers are the most fun way to use your time'
var firstPhrase = "Computers are the most fun way to use your time";
alert(firstPhrase);
这应该起作用:
var phrase = 'Computers are the most fun way to use your time';
console.log(phrase.replace(/([a-zA-Z)/g, function(c) {
return (c.toUpperCase().charCodeAt(0) - 64) + c;
}));
要向OP解释而不是脱口而出一堆代码吗?空格字符转换为“-32”。是的,当然。这种方法使用一个RegExp来匹配输入字符串中的每个字符,并通过一个函数传递每个匹配项,该函数获取大写字符代码(a=65),然后减去64,得到一个从1开始的“字母索引”。然后返回代码和匹配项作为替换。