Guide to slicing strings specifically with numerical characters at the end

I've encountered a challenge. I need to slice the last two characters in a string, but only for strings that contain numbers. I attempted using "nome": element.nome.slice(0,-2) and now I require some sort of validation. However, figuring out how to do this is proving to be difficult!

Below is my code snippet:

this.aux3.forEach(element => {        
    this.novasColecoes.push({
        "produtos": element.produtos,
        "nome": element.nome.slice(0,-2),          
        "referencia": element.referencia,
        "selecionado": false
    });        
})

Answer №1

If you need to extract specific information, regex can be a helpful tool.

const hasNumber = /\d/;

this.arr2.forEach(item => {        
    this.newItems.push({
        "products": item.products,
        "name": hasNumber.test(item.name) ? item.name.slice(0,-2) : item.name,
        "reference": item.reference,
        "selected": false          
    });        
})

Answer №2

Is this what you're looking for?

// Here is a new function
 function checkIfNumber(value) {
   return !isNaN(value);
  }

// Using forEach method

  this.arrayOfElements.forEach(item => { 
    let tempValue = item.name;
    if(checkIfNumber(tempValue)){
      tempValue = item.name.slice(0,-2);
    }
        this.newCollections.push({
          "products": item.products,
          "name": tempValue,          
          "reference": item.reference,
          "selected": false,
      
        });        
      })

Answer №3

Here is a concise solution that I would suggest:

element.nome.split('').some(b => b.match(/\d/)) ? element.nome.slice(0,-2) : element.nome

To begin, we split the string using the split method, resulting in an array of characters:

"test123".Split('');
// produces
let splitString = ['t','e','s','t','1','2','3'];

We can then apply the "some" function on the new array. This function returns true if any of the conditions are met.

In this case, we use a regular expression (RegExp), /\d/, which signifies "contains a digit". This allows us to filter out the digits.

// For our example, match will return true for 1, 2, and 3, causing some to return true
var containsDigit = splitString.some(s => s.match(/\d/))

Next, we utilize a Ternary operator. If the condition is true, we return "element.nome.slice(0,-2)", otherwise we return the original "element.nome".

{nome: containsDigit ? true : false}

When applied to your specific scenario:

this.aux3.forEach(element => {        
        this.novasColecoes.push({
          "produtos": element.produtos,
          "nome": element.nome.split('').some(n => n.match(/\d/)) ? element.nome.slice(0,-2) : element.nome,          
          "referencia": element.referencia,
          "selecionado": false          
        });        
      })

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

Dividing a collection of URLs into smaller chunks for efficient fetching in Angular2 using RxJS

Currently, I am using Angular 2.4.8 to fetch a collection of URLs (dozens of them) all at once. However, the server often struggles to handle so many requests simultaneously. Here is the current code snippet: let collectionsRequests = Array.from(collectio ...

When the button is clicked, (ngSubmit) will be triggered

In my Angular2 Form Component, I have implemented two buttons with different functionalities. Button Submit: This button submits all the values to the API. Button Add: This button adds an object to an array. Here are the two methods: onSubmit() { this. ...

How can I efficiently iterate through the array of index IDs and then iterate individually through the communes, categories, and locations?

Currently, I am developing a nodejs typescript API where I am retrieving an array of objects using a map loop. The data for "communes", "category", and "location" is fetched from another API function based on the issuerId. However, I am facing issues with ...

Gathering adorned categorizations (sans any listed category divisions)

My current setup involves an event dispatcher class that triggers listeners on specified occurrences. I've successfully implemented registering event listeners via decorators, but I feel like there may be a better solution out there. At the moment, e ...

Instructions for setting 0 as a valid value in Html code and displaying it

I have a query regarding HTML code within an Angular app. My inquiry is, is there an alternative method to check for null or undefined values in an ngIf statement? The code I am working with looks like this: <div ngif= "value !== null and value ! ...

Combining Vue with Typescript and rollup for a powerful development stack

Currently, I am in the process of bundling a Vue component library using TypeScript and vue-property-decorator. The library consists of multiple Vue components and a plugin class imported from a separate file: import FormularioForm from '@/FormularioF ...

Leveraging the spread operator in cases where the value is null

Is there a more elegant solution for handling null values in the spread operator without using if-else statements? In this specific case, I only want to spread assignedStudents if it is not undefined. When attempting to do this without using if-else, I e ...

Integration of Mocha with WebStorm

WebStorm offers a useful feature that adds a small arrow next to describe() and it() keywords when writing tests with Mocha, allowing for easy manual execution. However, there is a challenge: I require additional setup before each test, leading me to use ...

Using Dropbox for seamless navigation

My navigation using Dropbox is not redirecting to the selected page as expected. Below, I have provided code and a demo for your reference. App Routing Module import { NgModule } from '@angular/core'; import { CommonModule } from '@angular ...

Merging an assortment of items based on specific criteria

I have the following TypeScript code snippet: interface Stop { code: string } interface FareZone { name: string; stops: Stop[]; } const outbound: FareZone[] = [{name: 'Zone A', stops: [{ code: 'C00'}] }, {name: 'Zone B ...

Error: Unable to access the 'myDate' property as it is not defined

I've been working on a simple code, but I keep encountering a browser error. The expressjs logs also show an error message. TypeError: Cannot read property 'myDate' of undefined at getReportTable (XXX\dist\controllers&bsol ...

Personalized ornamentation using TypeScript

Is there a way to access the variables of the class when using a decorator? @ExampleDecorator() export class UserController { private userData: string = "example"; } export const ExampleDecorator = (config: IConfigSettings) => (target: Object) =&g ...

I am facing an issue where I am unable to retrieve a static variable from a global component within a subscribed component in Angular 7

I keep encountering an undefined variable issue when inside the subscribe function. import { AppSetting } from '../config/app-setting'; this.api.userLogin(this.loginForm.value.emailid,this.loginForm.value.password).subscribe( data => { ...

What is the best way to link three different types of http requests in succession and adaptively?

Is it possible to chain together 3 types of http requests correctly, where each request depends on data from the previous one and the number of required requests can vary? In my database, there is a team table with a corresponding businessId, a supervisor ...

In TypeScript, the argument 'xxx' cannot be passed to a parameter expecting a 'string' type

When I try to create a new Error object with the message {code: 404, msg: 'user is not existed'} in TypeScript, I receive the following error message: [ts] Argument of type '{ code: number; msg: string; }' is not assignable to paramete ...

Determine the data type of the value for the mapped type

Is there a way to access the value of a type like the following: interface ParsedQs { [key: string]: undefined | string | string[] | ParsedQs | ParsedQs[] } I am looking for a method to retrieve the ParsedQsValue type without directly duplicating it from ...

VSCode prioritizes importing files while disregarding any symbolic links in order to delve deeper into nested node

I'm encountering a problem with VSCode and TypeScript related to auto imports. Our application includes a service known as Manager, which relies on certain functions imported from a private npm package called Helpers. Both Manager and Helpers make us ...

What is the best way to fake the retrieval of '$location' using mock for angular.element(document).injector() in jasmine 3.6?

Currently, I am encountering an issue. I am unsure of how to mock the following method: private angularLocation = angular.element(document).injector().get('$location'); In my hybrid angular application, this method is crucial for navigating betw ...

When an input event is dispatched in a unit test, the value changes of a form are not activated

Currently, I am testing a scenario where I need to verify if a value changes on the form when input is typed in. This particular project utilizes Nrwl nx as well as jest for testing purposes. The component code snippet is as follows: export class InputNu ...

Unit testing of an expired JWT token fails due to the incorrect setting of the "options.expiresIn" parameter, as the payload already contains an "exp" property

I am having trouble generating an expired JWT token for testing purposes and need some guidance on how to approach it. How do you handle expiration times in unit tests? This is what I have attempted so far : it('should return a new token if expired& ...