Verify whether a string initiates with any of the strings contained in a specified array

Is there a way in JavaScript to determine if a string begins with any of the strings contained within an array?

For instance,

You have an array comprised of strings:

const substrs = ['the', 'an', 'I'];

And you also possess a string:

const str = 'the car';

What steps can be taken to ascertain whether str starts with any string from the substrs array?

Answer №1

To determine if a string starts with specific substrings, you can utilize both Array.prototype.some and String.prototype.startsWith, which are ES6 features:

const substrs = ['the', 'an', 'I'];
function checkIfStringStartsWith(str, substrs) {
  return substrs.some(substr => str.startsWith(substr));
}

console.log(checkIfStringStartsWith('the car', substrs)); // true
console.log(checkIfStringStartsWith('a car', substrs)); // false
console.log(checkIfStringStartsWith('i am a car', substrs));  // false
console.log(checkIfStringStartsWith('I am a car', substrs));  // true

If you require a case-insensitive comparison, you should also convert the string to lowercase:

const substrs = ['the', 'an', 'I'];
function checkIfStringStartsWith(str, substrs) {
  return substrs.some(substr => str.toLowerCase().startsWith(substr.toLowerCase()));
}

console.log(checkIfStringStartsWith('the car', substrs)); // true
console.log(checkIfStringStartsWith('a car', substrs)); // false
console.log(checkIfStringStartsWith('i am a car', substrs));  // true (case-insensitive)
console.log(checkIfStringStartsWith('I am a car', substrs));  // true

Answer №2

To tackle this, you can create a regex pattern with the keywords from the substrs array and then apply the test() method to the input string to validate for a match:

const substrs = ['apple', 'banana', 'orange'];
const str = 'apple pie';
regexp = new RegExp('^(?:' + substrs.join('|') + ')\\b');
console.log(regexp);
if (regexp.test(str)) {
    console.log("MATCH");
}

I've also included the display of the regular expression used for better understanding.

Answer №3

const subwords = ['apple', 'banana', 'orange'];
const word = 'apple pie';

let output = subwords.filter(w => word.includes(w));

console.log(output);

Answer №4

function verifyWord(arr, sentence) {
    const first = sentence.substr(0, sentence.indexOf(" "));
    return arr.includes(first);
}

const words = ['thee', 'an', 'I', 'The', 'the'];
const text = 'the car';

console.log(verifyWord(words, text)); //output: true

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 retrieve the value of an ASP label that has been set using jQuery?

Currently, I am developing a web application in asp.net, and I have a label control on my .aspx page. My goal is to set the text value of this label using jQuery and then access this value in my .cs file. <asp:Label ID="lbltext" runat="server" Text=""& ...

What is the best way to reset the selected label in a React Material AutoComplete component when the state is

I currently have a state declared as: const [searchEntryNo, setSearchEntryNo] = useState(''); In addition, there is a function set up to clear the state when needed. const handleClear = () => { setSearchEntryNo(''); }; Ne ...

Is it possible to have an object nested within a function? How about a function within a function? I'm determined to grasp

0 Can someone explain to me how the function express() works? I'm having trouble understanding how you can call a function when stored in a variable like const app = express(); Then calling a function like listen() as if it were an object: app.list ...

What could be causing my Vue application to not launch after executing `npm run serve`?

These past 24 hours have been a struggle for me. I recently embarked on the journey of learning Javascript, and my choice of JS framework was Vue JS. However, when I run npm run serve, my Vue JS app bombards me with numerous errors that seem to make no se ...

What is the rationale behind allowing any type in TypeScript, even though it can make it more challenging to detect errors during compile time?

Why is it that all types are allowed in TypeScript? This can lead to potential bugs at runtime, as the use of type "any" makes it harder to detect errors during compilation. Example: const someValue: string = "Some string"; someValue.toExponentia ...

Activate the textbox without utilizing `.focus()` method

I am encountering an issue with a small iframe on my page. The content within the iframe is larger than the window itself, requiring users to scroll around to view it in its entirety. Within this iframe, there is a button that, when clicked, triggers an an ...

Retrieve a specific value from an array within Firestore

I am facing an issue where I can only retrieve the values I need from the array by adding a specific string like "اقلام" or "سبورة". However, I want the value to be passed as a prop from another component or screen. Is there a way to resolve this ...

When the input CTRL+C is entered in the console, Node.js / JavaScript will output

I have a script that I use to restart another script. Here is the code snippet: catch(err){ console.log(err) webhook.send(`Error monitoring **www.-.com**, restarting monitor.`) await browser.close() await sleep(monitorDelay) return chec ...

Adjust the counter by increasing or decreasing based on the selection or deselection of tags

Currently, I am utilizing Next.js to manage a question form that consists of multiple questions with multiple answers. Users have the option to select one or multiple tags for each question. When a user selects one or more tags to answer a question, it sho ...

Guidelines for creating animation for a single point in SVG Polygon

Is there a way to animate the movement of a single polygon point within an SVG using velocity.js? Your assistance is greatly appreciated! <p>Changing...</p> <svg height="250" width="500"> <polygon points="0,0 200,0 200,200 00,20 ...

Tips for extracting the index of the chosen item from a dropdown using ReactJs and Material UI

This is the code snippet for Dropdown component implementation: <DropDownField name={formElement.name} label={formElement.name} value={formik.values[formElement.name] || ''} dropDownItems={formElement.name === &apo ...

The image momentarily pauses as the arrow keys are switched

I have a query regarding the movement of the main player image. While it generally moves smoothly Left or Right, there is an issue when quickly switching directions from right to left. When the left key is pressed while the right key is still held down, th ...

Retrieve an element generated by a React script without using the ref attribute

There is a chat button on my website generated by a script (zendesk chat) that creates an iframe with the ID "launcher". I am using Nextjs and I am trying to access this element, but I am unable to attach a ref since I do not have the code. I have been sea ...

Counting down with Jquery when times run out

Seeking assistance with implementing a jquery countdown timer on a webpage. The countdown I am utilizing is available at . My requirement is for the countdown to transition to another date once the current countdown expires. For instance, it should countdo ...

Loading an Angular2 app is made possible by ensuring that it is only initiated when a DOM element is detected

In my main.ts file, the code below is functioning perfectly: import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app.module'; platformBrowserDynamic().bootstrapModule(AppModule); H ...

Combining Versioning with BundleConfig.cs: A Comprehensive Guide

Encountering a recurring issue where changes made to CSS or Javascript files do not reflect in client browsers unless they manually refresh the page with ctrl+F5. This poses a challenge, especially in a school system with numerous users who may not be awar ...

Why are NodeJS and Jade/Pug variables not being recognized in the Jade script?

After successfully passing a variable to Jade like #{myvar}, I encountered an issue when trying to access it in a script block. Despite using typeof(myvar) and confirming that it was initially undefined, my attempts to display its value within the script b ...

How can I use AngularJS to show a JSON value in an HTML input without any modifications?

$scope.categories = [ { "advertiser_id": "2", "tier_id": 1, "tier_name": "1", "base_cpm_price": "", "retarget_cpm": "", "gender": "", "location": "", "ageblock1": "", "ageblock2": "", "ageblock3": ...

Nested data is the foundation of the Polymer framework's dom-repeat

Struggling with implementing Polymer's <dom-repeat>. Working with parent objects (folders) and child objects (contents within the folders) that are both generated from AJAX responses. The desired output should look like this: Folder child c ...

jQuery is currently displaying the value stored in the variable in a phrased format

Having trouble with the initial phase of a major project. I am attempting to showcase the JSON output received from the URL below. It displays the data perfectly when I directly enter the URL into a web browser. However, when I assign the URL to a variable ...