The argument labeled as 'RegExp' cannot be allocated to a parameter labeled as 'string'

My current task involves importing an Excel File in the following manner:

onFileChange(event: any) 
  {
    const inputFile: DataTransfer = <DataTransfer>(event.target); 
    const fileReader: FileReader = new FileReader();
    fileReader.onload = (event: any) => 
    {
      const binaryString: string = event.target.result;
      const workBook: XLSX.WorkBook = XLSX.read(binaryString, { type: 'binary', sheetStubs: true}); 
      /* sheetstubs true supposedly shows empty cells but isn't */
      console.log(typeof binaryString)

      const workSheetName: string = workBook.SheetNames[0];
      console.log(workSheetName)
      const workSheet: XLSX.WorkSheet = workBook.Sheets[workSheetName];

      this.data = <Array>(XLSX.utils.sheet_to_json(workSheet, 
      {header: 1, blankrows: true }));


    };
    fileReader.readAsBinaryString(inputFile.files[0]);

  }

My goal is to identify the index (essentially the column number) of any cell that contains the word 'cap' using regex.

I attempted to use regex as shown below to search for the term cap in any cell but encountered the following error,

Argument of type 'RegExp' is not assignable to parameter of type 'string'.
I am puzzled by the meaning of this error message and unsure how to proceed.

getManufacturerDescriptionColumn()
  {
    for (const row in this.data)
    {
      var descIndex = row.indexOf(/cap*/i)
      return descIndex
    }
  }

Answer №1

The String.indexOf() method requires a string as its first argument.

The syntax /<pattern>/ represents a regular expression literal and creates a RegExp object, not a string, as indicated by the error message.

To resolve this issue, use a string instead of a regular expression when calling String.indexOf():

row.indexOf('cap')

Note that this search is case-sensitive. If you need a case-insensitive search, using a regular expression would be more suitable.

In that case, you should utilize the String.search() method. This method expects a RegExp as its first parameter and returns the index of the first match within the string.


A few additional points to consider:

  • Your current loop will return the result of the first iteration even if no match is found.

  • The provided regular expression (/cap*/i) searches for 'ca' followed by zero or more 'p' characters. This means it will match 'ca', 'cap', 'capppp', etc.

You may want to modify your code like so:

getManufacturerDescriptionColumn() {
  for (const row in this.data) {
    let matchIndex = row.search(/cap/i);
    if (matchIndex > -1) {
      return matchIndex;
    }
  }
}

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

How can I achieve a smooth opacity transition without using jQuery?

Although I understand that JQuery offers functions for this purpose, I am interested in finding a solution using only pure javascript. Is there a way to change the CSS opacity setting over time? Perhaps utilizing a unix time stamp with millisecond precisi ...

The Typescript generics are unable to be assigned to type T

Take a look at my code snippet: interface IDoc { doSomething(): void } class IDocFoo implements IDoc { doSomething(): void { console.log('Do doSomething'); } } class IDocFactory { getIDocInstance<T extends IDoc>(): T { re ...

How can I link a Vue.js webpage with a WordPress site?

Looking to integrate a Vue.js 2 single page into an existing WordPress website? Perhaps you've already got an old WordPress site and now want to develop a new Vue tool or page that can be added seamlessly to the menu. How can this be achieved within W ...

Where does the 'Execution Context Destroyed' error originate from in my code?

Currently, I am developing a program to extract forum responses for the online University where I am employed. While I have managed to successfully navigate to the relevant pages, I encountered an issue when trying to include scraping for the list of learn ...

Unraveling the mysteries of JQGrid column sizing characteristics

My tree grid is causing me some headaches with its columns all having specified widths. The headers and columns below are completely out of sync, even when the data in them is short. In particular, when a column heading title is shorter than the width of ...

The dimensions of the d3 div remain constant despite any modifications to its attributes

In my angular application, I am trying to customize the width and height of div elements in d3 when I select a legend. Strangely, I am able to adjust the width and height of the svg element without any issues. Here is the issue illustrated: https://i.ssta ...

Tips for effectively using the JQuery animate function

Displayed below is my implementation of the jQuery animate method abstraction that works well. However, a challenge arises when trying to replace the hard-coded DOM element class in the function ani(){} with the 'this' keyword for versatility acr ...

What is the best method for filtering a dynamic object in Express.js?

Utilizing express for my REST API, I am looking to implement some filtering on my Posts based on req.query. Within the post structure, I have integrated a dynamic Object called options. Here is an example of my post structure: { "category": [ ...

"Creating a function that reverts a CSS class to its previous state when clicked using CSS and jQuery

I've got a <div> that starts with a blue background color and has a jQuery onclick event that changes the color to red. I'm trying to figure out how to make the div's background color change back to blue when the button is clicked agai ...

The window.addEventListener function is failing to work properly on mobile devices

Hey there! I am facing an issue in my JS code. I wrote this code because I want the menu to close when a visitor clicks on another div (not the menu) if it is open. The code seems to be working fine in developer tools on Chrome or Firefox, but it's no ...

Using PHP, identify a URL within text, verify if the URL refers to an image or a website, and then display the

Currently in the midst of a project that involves processing text containing various words and URLs, specifically images. The task at hand is to identify whether each URL within the text points to an image or a website. If it's an image, display it us ...

Go through a website's JSON data and save necessary information into a document

My task is to extract data from website.json using the request module, then filter through this information and only save a specific value in a key:value format such as "thatvalue":thisvalue. This process needs to be done for all the available data. Sampl ...

Tips for identifying when a gif has completed a single playback using JavaScript

Is it possible to detect when a gif reaches its loop point using Javascript in order to mimic the preloaders used for flash content? I currently have a script that checks when a video has loaded, but I'm looking for a way to do this same check when a ...

Using Gmail with Nodemailer is throwing an error: "Cannot add property 'mailer' on a string with value 'SMTP'."

I am facing an issue with sending data from a form to my Gmail account. Whenever I click the submit button, I encounter the same error message repeatedly. Despite researching various problems related to nodemailer, none of them match the specific problem t ...

Tips for customizing table cell styling in editable cells with React material table

My code utilizes a material table with editable cells. However, I am encountering a strange style issue when I edit a cell in the table. Please refer to the image below. Can anyone suggest a solution to fix this problem? https://i.sstatic.net/Miiov.png ...

Struggling to explore all the features of the Year selection in the Angular ng Bootstrap datepicker?

Currently, I am utilizing Angular 8 in conjunction with ng Bootstrap Datepicker. The issue I am encountering is that the year range within the DatePicker dropdown for selecting a year is limited. Below is the code snippet I am using: <div class="form ...

An array of Promise<Employee> cannot be used as a parameter for an array of type Employee[]

I am currently facing an issue with loading my Collection of Employees from a Firestore Database and fetching a 'Workday' for each Employee, which is stored as a Document in a Subcollection named 'Employees'. Below is the code snippet I ...

Typescript declaration specifies the return type of function properties

I am currently working on fixing the Typescript declaration for youtube-dl-exec. This library has a default export that is a function with properties. Essentially, the default export returns a promise, but alternatively, you can use the exec() method which ...

Breaking down observables into smaller groups in RxJS

My goal is to execute a pool of observables in chunks with an interval added in between each chunk. I attempted the following code: let i = 0; from([].constructor(20)).pipe( concatMap(a => of(i).pipe(delay(1000))), // add a delay me ...

Utilizing the `in` operator for type narrowing is yielding unexpected results

Attempting to narrow down a type in TypeScript: const result = await fetch('example.com') if (typeof result === "object" && "errors" in result) { console.error(result.errors); } To clarify, the type of result before the if condition should be ...