Javascript, removeFromString

I'm currently working on a JavaScript function that takes in two strings. The first string is any sentence provided by the user, and the second string consists of letters to be removed from the original sentence. My approach involves converting both strings into arrays and then using slice/splice methods to eliminate the specified characters.

let sentencePrompt = prompt("Please enter any sentence: ");
let removePrompt = prompt("Please enter a string of letter(s) to be removed from your original sentence: ");
function withoutString(sentence, str)
{
    let sentenceArray = sentence.split("");
    let removeArray = str.split("");
    let sentenceLength = sentenceArray.length;
    let removeLength = strArray.length - 1;
    for(let i = 0; i < sentenceLength; i++)
    {
        if((sentenceArray.slice(i, i+removeLength)) === removeArray)
        {
            sentenceArray = sentenceArray.splice(i, i+removeLength);
        }
    }
    return sentenceArray;
}
let newSentence = withoutString(sentencePrompt, removePrompt);
console.log(sentencePrompt);
console.log(removePrompt);
console.log(newSentence);

However, my code simply returns the original sentence without removing anything. Can anyone provide some guidance or advice? Thank you!

Answer №1

If you're looking for a more straightforward approach, you can utilize the replace function in a different way

const inputSentence = prompt("Enter any sentence: ");
const charactersToRemove = prompt("Enter the letter(s) you want to remove from the sentence: ");

const newSentence = inputSentence.replace(charactersToRemove, '');

alert(newSentence);

Check out this live snippet on jsfiddle.

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

Divide and Insert a Gap in Phone Number

I need help formatting a telephone number so that there is a space between every third and seventh character. var phoneNum = "02076861111" var formattedNum = [phoneNum.slice(0, 3), phoneNum.slice(3,6), " ", phoneNum.slice(6)].join(''); console ...

Error: Attempting to access a property called 'name' on an undefined variable leads to a TypeError

I am a beginner with MongodB and nodejs. I have successfully implemented the GET method, which returns an empty array. However, when I tried to use POST in Postman for "categories," I encountered this error message: ExpressJS categories route app.js Err ...

What is the best way to sum up array elements until they equal a target number, and then create objects using these summed values?

Suppose I have an array containing 5 different values for width, with a maximum width of 6 that needs to be reached. How can I iterate through the array and construct an object with those values each time it hits the maximum value without exceeding it? Le ...

Issue with jQuery click event not activating on initial click but functioning properly on the subsequent click

I am currently implementing the jquery.ime editor in my project, which allows for multi-language editing capabilities. The library I am using can be found here. By default, the language JSON files are loaded on "change" events. However, I would like this f ...

What are the steps to testing an endpoint with Jasmine/Karma?

Within one of my components, there is a method that makes a call to an endpoint in the following manner... private async getRolesAsync(): Promise<void> { const roles = await this.http.get<any>('https://sample-endpoint.com').toProm ...

I'm currently experiencing a challenge with a project I'm tackling that specifically deals with chart.js

In my recent coding project, I created a script to gather user input and then present it in various chart formats. However, upon executing the code, the selected chart fails to display after inputting values and clicking on the "generate chart" button. Her ...

What is the reason behind FieldSelect returning a string instead of an object like FieldCheckbox?

FieldSelect component from Sharetribe documents is giving me a string, while FieldCheckbox is returning a JSON object. In a specific scenario, I want FieldSelect to store a JSON object. How can I achieve this? Below is the code snippet for reference: I& ...

Break big files into pieces and upload them incrementally with nodejs

I'm currently working on a project that involves uploading very large files in chunks to a server. The functionality on the server side is running smoothly, but I've encountered an issue with the client-side code. My approach so far has been to a ...

What could be causing the submission failure of the form post validation?

My Code: <form method="post" name="contact" id="frmContact" action="smail.php"> ... <label for="security" class="smallPercPadTop">Please enter the result:</label> <br /><h3 id="fNum" class="spnSecurity"></h3>& ...

Guide to resolving a blank webpage issue post running 'npm run build'

I am currently in the process of working on a project that involves Vue and Firebase. Unfortunately, I have encountered an issue where my development server is no longer rendering new routes from my Vue router after building and deploying to production. F ...

How do I retrieve the HSL value for a color selected using an input of type 'color' in JavaScript?

I am faced with a creativity block and don't know where to begin. My goal is to develop functions that can manipulate the HSL values once I have access to them. Specifically, I am interested in modifying the light value, which is why I require it in ...

Steps to retrieve an array from AJAX request and save it to a JavaScript variable

How can I retrieve the 'this.responseText' array from this function and assign it to a variable named 'teacherIDList'? Any suggestions? var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readySt ...

Is there a way to manipulate arrays into slices within a match clause?

I have a situation where I have an enum with variants that contain arrays of different lengths. When attempting to use a `match` statement on this enum: enum EnumArray { One([i32; 1]), Two([i32; 2]), } fn main() { let arr = EnumArray::One([1] ...

Struggling to access the height attribute from a CSS file

Hey there. I'm pretty confident that the solution to my query is quite simple. So, I have a .css file with this particular code snippet: div.site { text-align:center; border:2px solid #4b6c9e; padding:1px; margin-top:10px; font-size:medi ...

Maintaining form data while dynamically including more instances of a <div> element to the form

I am currently developing a SpringMVC Webapp with a view that contains a dynamic form. The dynamic elements of the form are listed below: At the moment, I am passing the variable ${worksiteCount} from my controller to the view (stored in my portlet sessio ...

Node/ejs not recognizing Javascript files

I have been working on implementing a JavaScript code to create a hamburger menu when the screen is at a specific size, but unfortunately, nothing seems to happen. Here is how my directory structure looks like: public imgs javascript menu. ...

What are the possible complications that could arise from implementing this system for designing web pages?

Feeling frustrated with the limitations and compatibility issues of CSS, I decided to create a new approach for structuring webpages. Instead of relying on CSS, I developed a javascript library that reads layout instructions from XML files and uses absolut ...

Refreshing the v-model in a child component

Within my parent component, the code structure is similar to this: <template> <ProductCounter v-model="formData.productCount" label="product count" /> </template> <script setup> const initialFormData = { ...

"Troubleshooting why the jQuery Click Function is malfunctioning specifically in

Can someone help me troubleshoot this animate out script? It works fine on chrome, but not on Firefox and I can't seem to figure out why. Any suggestions? The script is designed to animate certain elements when a specific link is clicked. <scrip ...

Tips for generating an input element using JavaScript without the need for it to have the ":valid" attribute for styling with CSS

My simple input in HTML/CSS works perfectly, but when I tried to automate the process by writing a JavaScript function to create multiple inputs, I encountered an issue. The input created with JavaScript is already considered valid (from a CSS ":valid" sta ...