Picking a Single Word from a Collection of Words in JavaScript

In need of assistance with selecting specific words from an array. Take for instance this array:

var list = ['Brothers', 'Browsers', 'Dermatologist','Specialist','Optometry']

To perform the selection, I utilize the following script:

var pattern = "Der";
var matched = list.filter(a => a.indexOf(pattern) >= 0);

The matched variable will store:

['Dermatologist']

When changing the value of the pattern variable to "ist", the result would be:

['Dermatologist','Specialist']

Desiring filtering that only matches from the beginning of each word. For example, setting pattern to "Bro" should return:

['Brothers','Browsers']

If the pattern is set to "ers", then the result should be an empty array:

[]

Seeking assistance on achieving this functionality. Can anybody help?

Answer №1

To achieve this, you can utilize the startsWith method.

var words = ['Brothers', 'Browsers', 'Dermatologist','Specialist','Optometry']

var keyWord = "Der";
var result = words.filter(word => word.startsWith(keyWord));

console.log(result)

Answer №2

To filter a list of words starting with "Bro" using regex, you can add a caret (^) before the pattern:

var words = ['Brothers', 'Browsers', 'Dermatologist','Specialist','Optometry'];

var pattern = /^Bro.*/;

var filteredWords = words.filter(word => pattern.test(word));

console.log(filteredWords);

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

jspm is having trouble locating the globalResources for a 'feature' plugin in an Aurelia application

Looking for guidance on setting up and utilizing a feature plugin with Aurelia docs? Find detailed instructions at I encountered an issue where paths to resources were being transformed by jspm or Aurelia. Upon specifying the current path as .aurelia.use. ...

The TypeScriptLab.ts file is generating an error message at line 23, character 28, where it is expecting a comma

I am attempting to convert a ts file to a js file. My goal is to enter some numbers into a textarea, and then calculate the average of those numbers. However, I encountered an error: TypeScriptLab.ts(23,28): error TS1005: ',' expected. I have in ...

Ways to retrieve information from the object received through an ajax request

When making an AJAX request: function fetchWebsiteData(wantedId) { alert(wantedId); $.ajax({ url: 'public/xml/xml_fetchwebsite.php', dataType: 'text', data: {"wantedid": wantedId}, typ ...

Calculate the total number of randomly generated integers using jQuery

Below are examples of the inputs I have generated: <input type="text" id="rfq_ironilbundle_quotes_offer_price_0" name="rfq_ironilbundle_quotes[offer_price][0]" required="required" class="form-control offered-price"> <input type="text" id="rfq_iro ...

Strategies for transferring information to a different component in a React application

Building a movie site where users can search for films, click on a card, and access more details about the film is proving challenging. The problem lies in transferring the film details to the dedicated details page once the user clicks on the card. An onc ...

How to use node.js to add JSON data to a JSON file without using an array?

I'm trying to update a JSON file without using an array with FS. The desired format of the file should be: { "roll.705479898579337276.welcomemessage": "There is a welcome message here", "roll.726740361279438902.welcome ...

Learn how to simultaneously play two audio files using the same identifier in JavaScript

I'm facing an issue with two audio files that have a progress bar and both have the same ID: <audio id="player" src="<?=base_url('mp3/'.$rec->file)?>"></audio> </p> ...

How to Implement Jquery Confirm in Laravel Form Opening?

I've set up a Form using the Laravel Form package. {!! Form::open(['action' => ['Test\\BlogController@destroy', $thread->id], 'method' => 'delete', 'onsubmit' => 'Confirm() ...

Issue with Node Webpack identifying the "Import" statement

I'm diving into the world of Node and Webpack, but I'm struggling with getting my project to compile properly. Every time I try to load it in the browser, I encounter the error message: Uncaught SyntaxError: Unexpected token import. Let me share ...

Converting dynamic content within a div into an interactive link

I am currently working with Longtail's JW Player and facing some difficulties with a basic function. Since I am not familiar with the programming language terminologies, I will describe the issue step by step: There is a JavaScript code that displays ...

Tips for organizing and nesting form data

Can I format my data in JSON like this: { attachments: { file: [ { name: 'pic1.jpg' }, { name: 'pic2.png' } ], username: 'Test', age: 1 } } Is it achievable us ...

Reading a Json file with keys in puppeteer BDD: A Guide

Greetings, I am new to the world of puppeteer. I have successfully created my basic framework and now I am trying to figure out how to read data from .json files. I attempted to use the readFile method in my helper class, but unfortunately, it resulted in ...

Encountering the error message "Cannot GET /" in a NodeJS Express

I've been experimenting with various approaches to resolve this issue, ranging from app.use(express.static(__dirname + "public")) to res.render. It seems to function correctly in my terminal environment but fails when I try to access it locally. Can a ...

What causes the text field and checkbox to move downward as I enter text?

I'm currently working on a mock login page using React and Material UI. I implemented a feature where the show/hide password icon only appears when the user starts typing in the password field. However, after making this change, I noticed that the pas ...

Using JQuery Validation Engine to perform validation with an AJAX call

I am currently in the process of verifying if a specific record already exists in the database before adding a new entry. ajax Call "ajaxRecordExistsCall": { "url": "Controller?action=GET_LIST", "extraDataDynamic": ...

Executing a function while adjusting a range slider

Having an <input type="range"> element on my website presents a particular challenge. To handle changes in this element, I am using the following function: $("#selector").bind("change", function() { //perform desire ...

When incorporating Typescript into HTML, the text does not appear in bold as expected

Issue with bold functionality in Typescript Hey there, I am currently involved in an Angular project and I came across a problem with a function in a Typescript file that is supposed to bold a specific segment of text formatText() { ......... ...

Creating synchronicity in your code within the useEffect hook

Is there a way to ensure that my function is fully completed before moving on, even though it's not recommended to add async to useEffect? Take a look at this code snippet: useEffect( () => { const RetrieverDataProcess = async () => ...

Nodemailer is having issues, what could be the problem?

I am having an issue with Nodemailer. While it works fine on localhost, it gives me an error message. Can anyone help me identify the problem here? Below is a code snippet in React.js: import React from 'react' import styles from './index.c ...

What is the reason behind having a selectedOptions property rather than just a selectedOption?

Why does the selectedOptions property of select return an HTMLCollection instead of just one HTMLOptionElement? As far as I understand (correct me if I'm wrong), a select element can only have one selected option, so why do I always need to access it ...