How to eliminate the ending character from an array using JavaScript

Is there a way to remove specific characters from an array in JavaScript?

var wording = ["She", "gives","me", "called", "friend"];
var suffix = ["s", "ed", "ing"];   
function removeChars(word) {
    for (let i = 0; i < suffix.length; i++) {
        if (word.endsWith(suffix[i])) {
            return word.slice(0, -suffix[i].length);
        }
    }
    return word;
}
var text = wording.map(removeChars);
console.log(text);
  • I need to remove 's' from the word 'gives', but keep 'S' in 'She'.
  • I also want to remove 'ed' from 'called'.

Answer №1

If any of the words in the array match a suffix from the given list, you can remove that suffix from the word.

var words = ["He", "receives", "a", "call","from", "his", "friend"];
var suffixes = ["s", "ed", "ing"];
const removeSuffix = word => {
  const foundSuffix = suffixes.find(suffix => word.endsWith(suffix));
  return !foundSuffix ? word : word.slice(0, -foundSuffix.length);
}
var updatedWords = words.map(removeSuffix);
console.log(updatedWords);

Alternatively, you can use a regular expression to achieve the same result:

const words = ["He", "receives", "a", "call","from", "his", "friend"];
const suffixes = ["s", "ed", "ing"];
const pattern = new RegExp(suffixes.join('|') +'$');
const stripSuffix = word => word.replace(pattern, '');
console.log(words.map(stripSuffix));

Answer №2

TECHNIQUE 1

let words = ["He", "takes", "us", "for", "granted"];
let suffixes = ["s", "ed", "ing"];   
function removeSuffix(word) {
    let result = word;
    suffixes.forEach(suffix => {
        if( word.endsWith(suffix) ) {
            result = result.slice(0, word.length - suffix.length);
        }
    })
    return result;
}
let modifiedText = words.map(removeSuffix);
console.log(modifiedText);

TECHNIQUE 2

let words = ["He", "takes", "us", "for", "granted"];
let suffixes = ["s", "ed", "ing"];   
let modifiedText = words
//find words and their matching suffices
.map(word => [word, suffixes.filter(suffix => word.endsWith(suffix))])
//use the matched suffix to modify word
.map(([word, suffixesArray]) => suffixesArray.length ? word.slice(0, word.length - suffixesArray[0].length) : word);
console.log(modifiedText);

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

In PHP, you can add a new value to an array using a specific key or create

My goal is to retrieve individual array values using PHP and store them based on a specific key. If the key does not exist, I want to create a new entry. Below is the language file that I am working with: $LNG['name'] = array( 1 => &apos ...

Harness the power of Selenium + JavaScript or WebDriverJS to run JavaScript code directly in the browser

After a thorough search for many days, I have come here seeking help. We are currently using javascript + selenium (webdriverjs) in our setup. Our goal is to pass data into the browser that is opened via selenium. Simply put, we want to be able to execut ...

confirmation box for deleting a row in a grid view

I am looking to enhance the delete confirmation box on my Gridview delete function. Currently, I am using a basic Internet Explorer box for confirmation but I want to display a more stylish confirmation box. Here is the JavaScript code snippet within my gr ...

Mastering the utilization of API routes within the Next JS 13 App Router framework

As a newcomer to React JS and Next.js, I recently made the switch from using the Page Router API in Next.js to utilizing the new App Router introduced in Next.js 13. Previously, with the Page Router, creating a single GET request involved nesting your "JS ...

Choose an option removed upon clicking

I need to remove the option with a value of 0 when the user selects from the dropdown list. Choose: <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <form:select id="CONTEXTE" path="CONTEXTE" onclick="go()" class="s ...

Show the array on the question label and the button label

As a newcomer to Swift, I am faced with the challenge of displaying questions and answers stored in arrays. My goal is to present the question in a text label and each answer as a clickable button. Both the text label and buttons have outlets that need t ...

Sharing a specific variable among various React components: Tips and tricks

Within my project, I have created two sibling components called home and history. The home component contains the following function: //home function handledata() { const key = uuidv4(); localStorage.setItem(key, JSON.stringify(formdata)); } Now ...

Tips for ensuring session token verification remains intact upon reloading

I am currently in the process of developing a website using the Next.js framework and I am seeking advice on how to prevent the reload effect that occurs when transitioning from the login page back to the main page for just a fraction of a second. Below i ...

Tips for creating a responsive Youtube embedded video

Check out this website for a good example: If you take a look, you'll notice that the header youtube video is responsive - it automatically resizes when the window size changes. Here are the <iframe> codes: <iframe id="bluetube-player-1" fr ...

The inability to set MongoDB documents to automatically expire with TTL indexes

I'm currently facing a challenge in my Node.js application where I need to implement a TTL index on a date field within a MongoDB collection so that it automatically expires at a specified date. To achieve this, the application retrieves the current ...

Encountering the "Component resolution failed" error in Vue 3 when using global components

When I declare my Vue components in the top level HTML file, everything works fine. Here is an example: <body> <div class='app' id='app'> <header-bar id='headerBar'></header-bar> ...

Could you guide me on how to utilize Sencha Touch for saving information in a JSON file?

I am in the process of creating a simple Sencha Touch application to become more comfortable with the platform. My goal is to have the store (currently set up as shown below) read and write data to/from a local JSON file. Additionally, I would like the sto ...

Not all elements of the list are being iterated through in the copy

list=[1,2,3,5,2,1] copy=list.copy() for value in copy: print(value) copy.remove(value) print(copy) Output 1 [2, 3, 5, 2, 1] 3 [2, 5, 2, 1] 2 [5, 2, 1] I have initialized a list called "list" and created a copy of it named "copy" using the co ...

Integrate header into Material-UI autocomplete module

Is there a way to add a sub-header to the Autocomplete component in Material-UI? Currently, my approach is as follows: <Autocomplete {...props} options={options} renderInput={(params) => <TextField {...params} label={label ...

Exploring Updates in Two Objects Using a Loop in JavaScript

Two different Objects are structured as follows: Obj1: { 0: {name:"", id: 0}, 1: {"age": "", id:0}, 2: {name:"", id: 1}, 3: {"age": "", id:1}, } After triggering a property, the structure ch ...

Running a command once the forEach loop is completed in Angular

Within the HTML, I have a function that is triggered by an ng-click: vm.items = []; vm.moveItems = function() { angular.forEach(vm.items, function (item) { $http({ method: 'PUT', url: &apos ...

Best practice for interpolating an array element using printf

While going through Schwartz's Learning Perl, I encountered an exercise that requires accepting multiple user input strings, with the first input serving as the width for right justified output of the subsequent strings. To clarify: 10 apple boy Th ...

Is it possible for Excel's Index-Match or a similar function to match one row but provide a different one as the

I need assistance with automating the process of determining what percentile each physician's salary falls into based on a chart that displays salaries for different medical specialties by percentile. In this case, all physicians are in one specialty ...

Storing CakePHP data in the model as an array instead of a datatable

I have a small amount of data to share in my application that doesn't warrant using a database table. I'm thinking of creating an array in the model and then accessing the data from Controllers through that array. Is this feasible? My website ha ...

Use $parse to extract the field names that include the dot character

Suppose I have an object with a field that contains a dot character, and I want to parse it using $parse. For instance, the following code currently logs undefined - var getter = $parse('IhaveDot.here'); var context = {"IhaveDot.here": 'Th ...