1

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

2 Answers 2

3

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(/[A-Z]/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).

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.