简体   繁体   中英

Replace letters in string with numbers

I have this string '=F*G'

I want to replace it to numbers to be '=6*7'

I have successfully managed to replace letters with number using this code

 var string = '=F*G'.toLowerCase().split('').filter(c => c >= 'a' & c <= 'z').map(c => c.charCodeAt(0) - 'a'.charCodeAt(0) + 1).join(' ') console.log(string);

but this code removes the '=' and '*' I need help keeping them in string after replacing letters with numbers

You can use String#replace with a callback replacer function. This replacer function can use String#charCodeAt() to produce an ordinal value for each alphabetical character in the string.

 console.log("=F*G".replace(/[AZ]/g, m => m.charCodeAt() - 64));

Use [a-zA-Z] or the i flag if you want to match both cases and generate different numbers per upper/lower letter. If you want to normalize both cases to produce the same digits, call String#toUpperCase() first before applying the provided code above (or use toLowerCase() as you're doing and change the ordinal subtraction value accordingly -- it doesn't matter).

You can't filter the characters, or they won't be in the output to union back together. Try this.

    var string = '=F*G'
    .toLowerCase().split('')
    .map(c => {
        if (c >= 'a' && c <= 'z') {
            return c.charCodeAt(0) - 'a'.charCodeAt(0) + 1
        }
        return c;
    })
    .join('')

   console.log(string);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM