Struggling with handling numbers and special symbols in the Letter Changes problem on Coderbyte

Hello I have been struggling to find a solution for my current issue. The problem lies within an exercise that requires changing only alphabetical characters, but test cases also include numbers and special characters which are being altered unintentionally.

Below is the code snippet I've been working with:

function LetterChanges(str) { 

    let newTxt = ""; // stores string after changing each character to the next in the alphabet
    let newTxt2 = '';
    //iterate through the string
    for(let i=0;i<str.length;i++){

        switch(str[i]){
            case ' ':
                break;
            case 'z':
                newTxt = 'a';
                break;
            case 'Z':
                newTxt = 'A';
                break;

            default:
                newTxt = newTxt.concat(String.fromCharCode(str.charAt(i).charCodeAt(0) + 1));
                break;
        }

        //uppercase vowels
        switch(newTxt.charAt(i)){
            case 'a': case 'e': case 'i': case 'o': case 'u':
                newTxt2 += newTxt.charAt(i);
                break;
            default:
                newTxt2 += newTxt.charAt(i);
                break;

        }
    }
    str = newTxt;

    return str; 

}

In order to handle special characters or numbers without altering them, I am considering using if/else statements or nested switches based on regular expressions. This would ensure that only alphabetical characters are modified while others remain unchanged. Do you think this approach would be effective?

I'm relatively new to JavaScript and have spent hours searching Google for a suitable solution.

Thank you

Answer №1

After several hours of researching and experimenting, I have finally discovered a solution:

function ConvertLetters(str) {
   let newStr = str.replace(/[a-z]/gi, function(char){
       switch(char){
           case 'z': return 'a';
           case 'Z': return 'A';
           default: return String.fromCharCode(1+char.charCodeAt(0));
       }
   });
   return newStr.replace(/[aeiou]+/g, function(vowel){
        return vowel.toUpperCase();
   });



}

Many thanks!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unsubscribing from a service method in Javascript using RxJS

After clicking a button, a function is triggered to execute. The function includes an method called "executeAction" that retrieves the current view and then passes it as a parameter to another view for future reference. async executeAction(action: ...

Performing AJAX requests to dynamically update multiple DIVs

Encountering difficulties with adding additional input fields to a page, each of which contains jquery code for appending more select boxes related to them. The base html setup is as follows: <p id="add_field"> … </p> <div class="show_sub ...

Instructions on inserting a new row beneath a selected row using jQuery

https://i.stack.imgur.com/AlwHm.png When the second column is clicked, the method below is called: function getListOfList(primaryId, isFlat, col) { alert(primaryId) $.ajax({ url : ("/" + serverURL + "/dataGrid/getChilds"), ...

What is the best way to extract multiple values from a JavaScript variable and transfer them to Node.js?

Script JavaScript script snippet embedded at the bottom of an HTML file: var savedValues = [] var currentId = document.getElementById("fridgeFreezer").value function handleChange() { // Logic to handle user input changes: var temp = document.ge ...

Error: The function $(...).draggable is not recognized" and "Error: The object $.browser is not defined

I encountered an error stating, TypeError: $(...).draggable is not a function. To resolve this issue, I added jQuery as follows: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> < ...

Developing several sliders and ensuring they operate independently of each other

I am currently in the process of developing multiple sliders for a website that I am building. As I reach the halfway point, I have encountered a problem that has stumped me. With several sliders involved, I have successfully obtained the length or count ...

Resolving the Persistence Problem of Navigation Bar Fading In and Out

I've been struggling for hours trying different methods to achieve the desired outcome, but unfortunately, none of them have worked as expected. My goal is simple: I want the fixedbar to fade in when the scroll position exceeds the position of the ph ...

What is the value of x in the equation 2 raised to the power of x equals 800

Similar Question: What is the reverse of Math.pow in JavaScript? 2^x=i If i is given, how can we determine x using Javascript? ...

What methods are most effective for evaluating the properties you send to offspring elements?

Currently, I'm in the process of testing a component using Vue test utils and Jest. I'm curious about the most effective method to verify that the correct values are being passed to child components through their props. Specifically, I want to e ...

Combining two input text strings

A React component I'm working on takes the user's first and last name to create unique usernames for them. class App extends Component { render() { return ( <div className="App"> First name:<br/> <input ...

Dealing with Uncaught Type Errors in the Fixed Data Table

I am attempting to implement a fixed data table using the following code snippet. var MyCompi = React.createClass({ getInitialState: function() { return { rows : [ {"id":1,"first_name":"William","last_name":"Elliott","email":"<a ...

Isolating Express.js Requests for Enhanced Security

In my Node.js Express app, multiple users send requests to the server for various actions such as earning points, changing email addresses, and interacting with other users. My server code utilizes several setTimeouts, leading me to question whether diffe ...

After implementing two hooks with null properties, the code fails to execute

Recently, I encountered an issue with this section of the code after upgrading react scripts from version 2.0 to 5.0. const { user, dispatch } = useContext(AuthContext); const { data } = useFetch(`/contracts/${user.contractType}`); if (!user) { ...

Managing various swipe interactions using HTML and JavaScript/jQuery

I'm in the process of creating a mobile multiplayer game using HTML5 and Javascript. The jQuery Plugin "touchwipe" is utilized to manage swipe events in various divs like this: $('#play1').touchwipe({ wipeLeft: function(){ if ...

What is the best approach to testing a function that relies on a reference to Firebase?

I am currently trying to write unit tests for a function within my application that interacts with Firebase, specifically by calling and updating a reference. However, I have encountered an issue while attempting to run the test - upon importing the file c ...

[Vue alert]: "Maximum" property or method is not declared in the instance but is being referenced during the rendering process

Here is my custom Vue component: Vue.component("product-list", { props: ["products", "maximum-price"], template: ` <div> <div class="row d-flex mb-3 align-items-center p-3 rounded-3 animate__animate ...

Registering dynamic modules within a nested module structure - Vuex

As stated in the Vuex documentation, a nested module can be dynamically registered like this: store.registerModule(['nested', 'myModule'], { // ... }) To access this state, you would use store.state.nested.myModule My question is h ...

Implement a one-second delay before nesting another animation

I'm currently utilizing a timeout function, but I am interested in using a delay instead. My goal is to have the second animation start when one second has passed from the beginning of the first animation, and it should be a linear animation. How can ...

The output from the NodeJS storage module function

Attempting to implement Two-Factor Authentication in my initial NodeJS project, which serves as a learning tool for Node. While the function correctly retrieves values from data_url, when I assign it to a variable and return data_url, it returns 'und ...

The Node.js script functions correctly on the first run but encounters failure in subsequent executions

I am in need of a Node.js script that can perform the following tasks: 1 - Trigger when an image is added to a specific S3 bucket. 2 - Generate a thumbnail of that image (360x203 pixels). 3 - Store a copy of the thumbnail in a separate S3 directory. ...