1

For an assignment, i am trying to recreate a small project I once made in ASP.NET.

It converted each letter of a text to its int value, then added 1 en reconverted it to a char and put them all back into a single string.

Now I am trying to do this in Angular, but I am having trouble converting my non-numeric strings to its int value.

I tried it with ParseInt(), but this only seems to work if the string is a valid integer.

Is there any way to parse or convert non-numeric strings to an int value and how?

3
  • Look here : ParseInt on letters Commented May 6, 2017 at 14:24
  • 1
    it seems like you will have to do the same thing you have done in your ASP.NET program; break your string into an array of char, then loop through the array and use char.charCodeAt() on each letter. Commented May 6, 2017 at 14:25
  • @Claies In ASP.NET I was simply doing (int)stringmsg[i] in a for loop, but the charCodeAt put me on the right track, so thank you. Commented May 6, 2017 at 14:56

2 Answers 2

5
'String here'.split('').map(function (char) {
    return String.fromCharCode(char.charCodeAt(0) + 1);
}).join('');

If you mean char code.

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

1 Comment

This is probably good for Javascript, but i'm looking for an Angular/Typescript syntax solution. Perhaps the javascript tag should be removed from the question.. But this and @Claies comment helped me
1

Thankx to the helpful insights of Claies and Damien Czapiewski I constructed the following solution.

Loop through each character in my string in a for loop.
Then, for each char I retrieved its value with charCodeAt()
And to return to a string value I used fromCharCode()

encode(msg:string):string {

    let result: string = "";

    if (msg) {
        for (var i = 0; i < msg.length; i++) {

            let msgToInt = msg.charCodeAt(i);

           // do stuff here

            result += String.fromCharCode(msgToInt);
        }
    }

    return result;
}

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.