Delete a character from a string in JavaScript by targeting a specific position starting from the end

I've been grappling with a problem involving removing a specific character at a known position from the back of a string. Here's the situation:

Currently, I have strings like:

'RX8567' 'A8532' '18256' 

I want to delete the first '8' I encounter in each string. However, I would prefer to tackle this issue from the end of the string, as I am uncertain of the number of alphanumeric characters at the beginning. From the back, I know that the character I want to remove will always be the 4th character. So, if the '8' is the fourth character of the string from the end, I want to remove it. I've managed to achieve this from the front with the following code:

    var string = 'A8532'            
    var string = string.slice(0,1) + string.slice(2);

This should result in:

'A532'

However, this only works if the '8' immediately follows the 'A'. Is there an alternate or simpler method of achieving this while working from the back of the string as described? Thank you in advance!

Answer №1

Here is a suggested solution for the given problem:

var code = 'RX8567';
//if '8' is the fourth character of the string moving from the back remove it
if (code.slice(-4, -3) === '8') {
    code = code.slice(0, -4) + code.slice(-3);
}

code.slice(0, -4) will provide all characters except the last four

code.slice(-3) will give the last three characters


Alternatively, you can use a regular expression for the same task:

var code = 'RX8567';
code = code.replace(/(?:^(.*)8(.{3})$)/, '$1$2');

(?: is used to create a non-capturing group (the entire expression)

^ signifies the start of the string

(.*) matches any number of characters (represented by group $1 in the replacement string)

8 is the specific character '8' to be matched

(.{3}) matches three characters of any kind (represented by group $2 in the replacement string)

$ denotes the end of the string

) closes the bracket for the initial group in the regular expression


For processing a large number of such codes, the first solution may offer significantly improved speed.

Answer №2

Give this a shot:

function eliminateEight(code) {
    let eightPosition = code.indexOf('8');
    return eightPosition === -1 ? code : code.slice(0, eightPosition) + code.slice(eightPosition + 1);
};

let codes = ['RX8567', 'A8532', '18256'];

for (let i = 0; i < codes.length; ++i) {
    console.log(codes[i] + ' transforms into ' + eliminateEight(codes[i]));
}

Answer №3

function removeEight(value){

  // Grab the 4th character from the end of the string
  var char4 = value.charAt(value.length - 4);
  
  // If the character is '8', remove it from the string
  value =  char4 === '8' ? value.replace(value[value.length - 4], '') : value;
  console.log(value);
}

removeEight('RX8567');
removeEight('A9532');
removeEight('18258');

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

Is there a way in Vue to efficiently route multiple instances belonging to the same component while ensuring they maintain their individual states?

It's a bit difficult to capture the exact issue in the title. Here is the scenario: // In the main layout page <keep-alive> <router-view /> </keep-alive> // And I have a route { path: "something/:id", name: "someth ...

Exploring the Module System of TypeScript

I am working with a TypeScript module structured like this: let function test(){ //... } export default test; My goal is for tsc to compile it in the following way: let function test(){ //... } module.exports = test; However, upon compilation, ...

Differences between MobX local state and global state

I am currently working on a React project using mobx to manage the application state. For dump components that interact with external data sources (such as ajax calls, filtering or mapping arrays), I simply manipulate the data in those components. Howeve ...

Validating input in Angular UI Bootstrap Datepicker

I have integrated a datepicker from angular-ui/bootstrap. However, I am facing an issue where the user can freely type in the input field instead of selecting a date. Here is a snippet of my code: session.js session.getDateFormat = function() { ...

Displaying the votes through an advanced system called Ajax voting system

I've encountered a challenge while using an ajax voting system in my project. The issue is that I'm utilizing a div with an id to showcase the votes, but whenever someone clicks on vote up or down in any of the posts (which are generated through ...

Troubleshooting issues with NodeJS and Express authentication middleware functionality

I am currently working on implementing the isUserAuthenticated function to run on every server request. This function is required in the app.js file and utilized using app.use(authenticate.isUserAuthenticated). In my project, there is an /authenticate rou ...

Executing JavaScript - Triggering an 'onClick' event within a For loop to dynamically load multiple hyperlinks

I am currently working on creating a listview using JSON data. However, when I call an 'onclick' function from a For loop, the link opens in a new window and loads three URLs into the browser's URL input. Is there a way to modify the code be ...

Uncovering the Power of Shadow DOM within HTML

Lately, I've noticed a lot of buzz surrounding Shadow DOM. During a video I watched about the launch of Angular 2, the speaker kept mentioning Shadow DOM without much explanation. Can someone clarify what exactly Shadow DOM refers to? ...

Unlocking the Power of $http and Stream Fusion

I'm interested in accessing the public stream of App.net. However, when I attempt to retrieve it using a simple $http.get(), I only receive one response. $http .get('https://alpha-api.app.net/stream/0/posts/stream/global') .success(func ...

Using node-native to authenticate in MongoDB is a surefire way to ensure the

I'm currently facing an issue while attempting to save a document in MongoDB within my Nodejitsu/MongoHQ application. Everything works perfectly locally, but the MongoHQ database requires authentication and it fails even with the correct user/password ...

The latest version of fork-ts-checker-webpack-plugin, version 5, cannot be reached from @vue/cli-plugin-types

Currently, I am updating the build container in my project from node:10-alpine to node:14-alpine. However, when I run npm ci (after rebuilding package-lock.json), I encounter the following error: npm ERR! fork-ts-checker-webpack-plugin-v5 not accessible fr ...

Troubleshooting: Android compatibility issues with dynamic source for HTML 5 video

My HTML5 video with dynamic source loaded using JavaScript is functioning properly in a web browser but encountering issues within an Android PhoneGap build application. Take a look at the code snippet below: JavaScript code: $('#video_player' ...

Reveal unseen information on the webpage upon clicking a link

I have successfully implemented a fixed header and footer on my webpage. The goal is to make it so that when a user clicks on a link in either the header or footer, the content of that page should appear dynamically. While I have explored various styles, ...

Issue with Yeoman webapp generator and Gulp, encountering error when using Gulp-jade package

I'm encountering some difficulties integrating jade with yeoman's gulp webapp generator. The watch task is functioning properly, but when I attempt to build the project, I encounter the following error: stream.js:94 throw er; // Unhandled ...

Kineticjs is not performing up to par

I apologize if this question has already been asked, but I haven't been able to locate it. I am working on a project that involves a canvas displaying approximately 400-500 rectangles, each ranging in height and width from 20-30 pixels. The goal is t ...

What is the most effective way to use a withLatestFrom within an effect when integrating a selector with props (MemoizedSelectorWithProps) sourced from the action?

I am struggling to utilize a selector with props (of type MemoizedSelectorWithProps) in an effect inside WithLatestFrom. The issue arises because the parameter for the selector (the props) is derived from the action payload, making it difficult for withLat ...

Having trouble enabling push notifications on Android with ngCordova

Having trouble with push notifications through the ngCordova plugin. Followed the sample code from (with a slight change - no deviceready listener, code inside ionicPlatform.ready listener) Below is the code snippet: angular.module('myApp', [& ...

Is there a way to exclusively view references of a method override in a JS/TS derived class without any mentions of the base class method or other overrides in VS Code?

As I work in VS Code with TypeScript files, I am faced with a challenge regarding a base class and its derived classes. The base class contains a method called create(), which is overridden in one specific derived class. I need to identify all references ...

Implementing JavaScript to Take an Array of Integers from an HTML Input Field and Sort It

Task: Retrieve 10 Array Values from HTML Input Field and Arrange Them in Ascending Order In order to add 10 values from an HTML input field to a JavaScript array, I have created an input field through which data is passed to the array in JS. Two labels ar ...

date-fns | display date

Issue I have a function that formats date strings as shown below. import { format, parseISO } from "date-fns"; export function convertDate(myDate, displayFormat) { return format(new Date(parseISO(myDate)), displayFormat); } My articles con ...