Placing gaps after every group of four digits

I am currently working with Ionic 4 and Angular 8, attempting to insert a space every 4 digits entered by the user. However, the function I have written seems to be malfunctioning, as it inserts a space after each action the user takes following 4 numbers.

Here is the function I am using:

maskInput(input){

    let masked:
    Array<String> = input.replace(" ", "").split("");

    let res = "";

    for(let i = 0; i< masked.length; i++) {
    if(i % 4) res += masked[i]

      else res += " " + masked[i]

    }
    return res
  }

Is there an issue in my implementation of (ngModelChange) within ion-input? Could the problem lie within the for loop?

To address the spaces problem, I made the following code adjustment:

Array<String> = input.replace(" ", "").split(" ").join("").split("");

However, it still appears to count spaces as input.

Answer №1

I'm not quite sure what you're asking, but if you're looking for a way to insert spaces every 4 digits in a function, here's one :

const input = "765389764";

function addSpaceEvery4Digit(input) {
  let newInput = "";
  for (let i = 1; i < input.length; i++) {
    newInput += input.charAt(i);
    if ((i % 4 === 0) && i < input.length - 1) {
      newInput += " ";
    }
  }
  return newInput;
}

const res = addSpaceEvery4Digit(input);
console.log(res);

EDIT :

You should iterate over the string itself, not an array of strings, in your code :

change :

let masked:Array<String> = input.replace(" ", "").split("");

with :

let masked:string = input.replace(" ", "");

Answer №2

Issue resolved by adjusting the split function in my code. Here is the updated function that successfully fixed the problem: (split, join, split)

maskInput(input) {

    const masked:
    // tslint:disable-next-line: ban-types
    Array<String> = input.replace(' ', '').split(' ').join('').split('');

    let res = '';

    for (let i = 0; i < masked.length; i++) {
    if (i > 0 && (i) % 4) { res += masked[i]; }

      // tslint:disable-next-line: one-line
      else { res += ' ' + masked[i]; }

    }
    console.log(input);
    return res;
  }

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

Error in Svelte/Typescript: Encounter of an "unexpected token" while declaring a type

Having a Svelte application with TypeScript enabled, I encountered an issue while trying to run it: [!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript) src\api.ts (4:7) 2: 3: export default class API { 4: ...

Popover disappears when scrolling the page, but its position remains constant in Angular 4+

After clicking on an icon, a popover appears. I've noticed that the popover has a delay set, but when I scroll, the popover also moves along with it. Is there a way to keep the popover in place and not have it affected by scrolling? <md-badge cla ...

Tips for effective page management

After creating a navbar in my project, I've come to the realization that it requires a component for each page and subpage. This seems redundant especially when dealing with multiple navigation options like shown in this image. Is it necessary to crea ...

Having trouble retrieving the `Content-Disposition` information from the backend response

I've been attempting to retrieve the value of Content-Disposition from the backend response, but unfortunately, I have not been successful. Here is the code I have been working with: public getQuoteImage(sharedQuote):Observable<any> { retu ...

Angular routing functions flawlessly on Chrome Mac but encounters issues on Chrome iOS

Encountering a strange issue. My routing is properly configured and has been verified multiple times. Oddly enough, page1, page3, and page5 are functioning correctly, while page2, page4, and page6 fail to redirect as expected. Upon clicking the redirect ...

Navigating with Ionic - Initial Screen

I'm currently delving into the realm of the ionic framework, specifically focusing on routing functionalities which has me a bit perplexed. Previously, my app was functional; however, I now wish to incorporate additional views. Beginning with my home ...

Ways to Determine the Source and Destination Containers in Angular Drag and Drop

Incorporating a drag and drop feature into my Angular application using Angular Material's CDK has been successful. However, I am facing challenges in identifying the source and target containers during the drop event. I have examined the drop event ...

The issue arises when Jest fails to align with a custom error type while utilizing dynamic imports

In my project, I have defined a custom error in a file named 'errors.ts': export class CustomError extends Error { constructor(message?: string) { super(message); Object.setPrototypeOf(this, Error.prototype); this.nam ...

Potential null object detected when using a ref(null)

After reading the Vue Composition API documentation, it seems I should be utilizing ref(null) within a sub-component located inside <template>...</template>. Within this sub-component, there are methods such as open(), and my current approach ...

Utilizing dynamic arguments in TypeScript to recycle types

Can I accomplish this with TypeScript? Here is the source code I currently have: interface FormStore<T> { type: T; } interface Form<T> extends FormStore<T> { email: T; phone: T; password: T; } interface FormState<R> { fo ...

What kind of ng-template is used for enforcing strict typing in Angular?

I have an Angular application running on version 14, and let's consider a component inside it where I have the following HTML: <button (click)="myfn(template)">Click Me</button> <ng-template #template> <some html here& ...

Tips for retrieving input values when they are not available in HTML documents

In this code snippet, I am creating an input element with the file type without adding it to the DOM. My goal is to retrieve the value of this input once the user selects a file. Even though the input is not part of the HTML template, I still want to acces ...

Do we really need TypeScript project references when transpiling with Babel in an Electron project using Webpack?

Currently, I am in the process of setting up my project configuration and have not encountered any errors so far. However, based on my understanding of the Typescript documentation... It appears that Project references are not essential when using babel-l ...

Obtain the numerical representation of a weekday based on the name of

I am working with an array that looks like this: result = ['Saturday','Sunday'] My goal is to return the index for each of the days above, like this: detail= [6,7] I attempted the following approach to achieve this, but unfortunatel ...

Develop a flexible axios client

I have a basic axios client setup like this: import axios from "axios"; const httpClient = axios.create({ baseURL: "https://localhost:7254/test", }); httpClient.interceptors.request.use( (config) => config, (error) => Prom ...

Encountering unproductive errors with custom editor extension in VS Code

I'm currently developing a custom vscode extension for a read-only editor. During testing, I encountered a rather unhelpful error message. Can anyone offer some insight on what might be causing this issue? 2022-11-25 11:36:17.198 [error] Activating ex ...

Navigating to the root of a child component in Angular2 routing can be achieved by using the Router

In the App.ts file, I have configured the following router: @RouteConfig([ {path: '/', redirectTo: ['Login']}, {path: '/login', name: 'Login', component: LoginComponent}, {path: '/dashboard', n ...

Error: When trying to run the `ng build` command in Git Bash, TypeScript module cannot be

When attempting to execute ng build using Git Bash, I encountered this error message, even though I had previously executed npm install -g typescript. Where should I place the typescript installation so that Git can detect it? Error $ npm install -g typ ...

Why am I receiving a peculiar type error with @types/jsonwebtoken version 7.2.1?

My current setup includes node v6.10.3, typescript v2.3.4, and jsonwebtoken v7.4.1. Everything was running smoothly until I decided to upgrade from @types/jsonwebtoken v7.2.0 to @types/jsonwebtoken v7.2.1. However, after this update, an error started poppi ...

Using template strings in a Mongoose update query when working with TypeScript

When working with a mongoose update query in typescript, I am trying to incorporate a template string. The specific field I need to update is a Map named messages, which consists of string keys and array values of type Message. interface Message { conte ...