Discover the position of characters within a given string

I'm trying to accomplish a task similar to this:

If the array [ "a", "b", "c" ] includes any of the characters in the constant word = "abracadabra", I want to retrieve that character along with its position in const word.

My attempt so far looks like this:

const word = "abracadabra";
const input = ["a", "b", "c"];
for (let i = 0; i< word.length; i++) {
  if (input.includes(word(i))) {
  console.log(i + (word(i)));
  }
}

However, it's not working as expected. Can someone assist me with the logic and syntax? I am new to coding, thank you for your time and help!

Answer №1

To access a field of an array, remember to use square brackets instead of parentheses which are meant for calling functions.

const term = "terminator";
const chars = ["t", "e", "r"];

for (let j = 0; j < term.length; j++) {
  if (chars.includes(term[j])) {
      console.log(j + term[j]);
  }
}

Answer №2

Since your query specified:

provide me with the character and its position in const word

you can utilize RegExp.prototype.exec

const word = "abracadabra";
const input = ["a", "b", "c"];

input.forEach(c => {
  const re = new RegExp(c, "g");
  let m;
  while (m = re.exec(word)) console.log(`${c} found at index ${m.index}`);
});

Another efficient method to accomplish the same task is by using Array.prototype.reduce():

const word = "abracadabra";
const input = ["a", "b", "c"];

const res = input.reduce((ob, c) => {
  ob[c] = [...word].reduce((a, w, i) => {
    if (w === c) a.push(i);
    return a;
  }, []);
  return ob;
}, {});


console.log(res);

This approach will generate an Object, with each character as a property containing an array of its positions in the word:

{
  "a": [0, 3, 5, 7, 10],
  "b": [1, 8],
  "c": [4]
}

Answer №3

const phrase = "abracadabra";
const letters = ["a", "b", "c"];
for (let index = 0; index < phrase.length; index++) {
  if (letters.includes(phrase[index])) {
    console.log(index + (phrase[index]));
  }
}

Remember to utilize the square bracket phrase[i] instead of phrase(i).

Answer №4

After formulating and posting the question, a better solution came to mind. I've now come up with a working code snippet:

const word = "abracadabra";
const inPut = ["a", "b", "c"];
for (let i = 0; i< word.length; i++) {
    for (let j = 0; j< (inPut.length); j++) {
        if (word.charAt(i).includes(inPut[j])) {
            console.log(i + (word.charAt(i)));

        }
    }
}

Answer №5

for(let i=0;i<input.length;i++){
  if(word.indexOf(input[i]) != -1){
    console.log('word includes ',input[i])
  }
}

My solution should help address the issue you're facing.

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

What is the best way to import an external file from the project's root directory using webpack?

I am currently working on a unique npm package that will allow for the integration of custom rules from the project root. This functionality is similar to how prettier searches for a .prettierrc file in the project root. For this particular package, I am ...

Tips for customizing your MUI slider design

import * as React from "react"; import Box from "@mui/material/Box"; import Slider from "@mui/material/Slider"; function valuetext(value) { return `${value}°C`; } export default function RangeSlider() { const [value, se ...

An error is thrown in Three.js stating that the array index 'i' is undefined at line 180, using TransformControls

While working with loaded .STL Files in Three.js using TransformControls, I'm experiencing an issue. Whenever I mouse hover or use the transformControls, my console logs "TypeError: array[i] is undefined three.js:180:9". Is anyone familiar with this e ...

Struggling to execute an AJAX request in JavaScript

I am a beginner in .Net development and I am trying to make a call to the client's server. When I test the code using POSTMAN, it works fine. However, when I use the same code/headers in JavaScript, I do not get the desired result. Here is the code I ...

The second attempt at an AJAX call is unsuccessful

I am currently developing a form that displays database results based on two entries: Automarke (brand) and Modell (model). You can view the entries here. The Modell dropdown dynamically changes based on the selected Automarke. Here is the code snippet I ...

Executing an HTML webpage with npm package.json file

I have recently discovered package.json files and am new to using them. I have created an HTML webpage using three files: HTML, CSS, and JavaScript. Currently, I open the HTML file directly in my browser but have been advised to use a package.json file a ...

Using AXIOS and VueJs to visually represent data with a two-dimensional array

I'm new to vuejs and I want to display my data response in a two-dimensional table. This is the data I have: [{ "origine": "", "nb": 15 }, { "origine": "?", "nb": 18 }, { "origine": "?L", "nb": 1 }, { "origine": "G", "nb": 298 }, { ...

What is the correct way to add an object to a specific array in express.js?

My goal in the following function is to write a JSON file with an array of data as strings. However, the push() function, which is commented out, is causing the code to not execute as intended. Everything works fine without that line of code, but I do need ...

What is the reason for utilizing the object name in the object's method rather than using "this"?

Looking at the code snippet above, you can see that store.nextId and store.cache are used in the add method. It makes me wonder why not use this instead? var store = { nextId: 1, cache: {}, add: function(fn) { if (!fn.id) { fn.id = this. ...

Toggle React like button

I am working on a component that displays the number of likes next to a 'like' button. I want to implement a functionality where clicking the button once adds to the number of likes, but if clicked again, it reverts back to the previous state. Th ...

Pair two arrays based on a specific key value

I'm currently facing a challenge where I need to associate two arrays of objects, and I could really use some help with this. Explanation : One array contains various reference products const array1 = [ {name: peanuts, referenceKey: 0}, {name: almon ...

I encountered an error while trying to add a document to Firestore using the 'add' method in Vue.js. Can someone provide guidance on how to

Whenever the function is triggered (on click), I aim to include a new document. Although it functions with .set(), my goal is for a new document to be created each time the form is submitted. The current error code I am encountering is: https://i.sstatic ...

What steps do I need to take to ensure my TypeScript module in npm can be easily used in a

I recently developed a module that captures keypressed input on a document to detect events from a physical barcode reader acting as a keyboard. You can find the source code here: https://github.com/tii-bruno/physical-barcode-reader-observer The npm mod ...

The functionality of the Bootstrap tabbed pane is not functioning correctly

I am currently in the process of creating a modal tabbed pane in bootstrap following the instructions provided in this guide. You can view the code and functionality on this fiddle. $(document).on("click","#tabs a",function(event) { alert("!!!"); ...

tips for setting the value of a checkbox to true in React Material-UI with the help of React Hooks

<FormControlLabel onChange={handleCurrentProjectChange} value="end" control={<Checkbox style={{ color: "#C8102E" }} />} label={ <Typography style={{ fontSize: 15 }}> C ...

Order a set of date strings in an array using JavaScript

Despite my attempts with underscorejs, I found that the min and max methods cannot handle strings as they return infinite. Is there a way around this limitation? Here is a sample array: dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"] ...

Exploring Laravel's method for retrieving data from multiple tables in the controller

In an effort to make my jQuery call more dynamic, I have a controller with the following method: public function api(Request $request , $project_id){ return Program::where('project_id',$project_id)->get(); } This results in: [{"id":178," ...

What is the best way to utilize Link for navigation in React with Material UI?

const pages = ['home', 'menu', 'reservation']; <Box sx={{ flexGrow: 1, display: { xs: 'none', md: 'flex' } }}> {pages.map((page) => ( <Link component={Link} to='/'>Home</L ...

Converting PHP variables to JavaScript variables: A step-by-step guide

I'm trying to figure out the most efficient method for retrieving PHP variables using AJAX and then transforming them into JavaScript variables. Imagine I have the following code in my PHP file: echo $total; echo $actual; Edit: JSON echo json_enco ...

Mastering the art of utilizing callbacks in AngularJS for consuming an API

Having trouble handling data from an API and structuring it effectively before passing it to the controller. I've created a factory that retrieves user data from the API, but the provideAllUserData function is causing issues. Below is my services.js: ...