Exploring text with regex that begins with a particular pattern

I'm on a mission to find specific keywords within text.

const matchHashtags = /(#\w+) ?/g;
const text ="this is #sample tag and other #another tag";
while ((hashtag = matchHashtags.exec(text))) {
      alert(hashtag);
}

Above, we successfully searched for words starting with #. Now, let's try finding words starting with "iphone~" below.

const matchHashtags2 = /(^|\s)\iphone~(\w+)/g;
const text2 ="I have iphone~seven~new and iphone~seven~ old phones";
while ((hashtag2 = matchHashtags2.exec(text2))) {
      alert(hashtag2);
}

I expect this query to find "iphone~seven" including the word after it. However, it returns: "iphone~seven, ,seven".

https://jsfiddle.net/gecj54a3/1/

Please help me resolve this issue. Thank you!

Answer №1

Is there an issue with the regular expression

const matchHashtags2 = /(iphone~\w+) ?/g;
?

Answer №2

This is one way you could approach it:

let sentence = 'I own two cats, three dogs, and four birds';
let words = sentence.split(' ');
for (let j = 0; j < words.length; j++){
    if(words[j].includes(',')){
        console.log(words[j]);
    }
}

Answer №3

Here's a helpful code snippet for extracting specific hashtags:

const hashtagPattern = /(^|\s)\iphone~(\w+)/g;
const text = "I have iphone~seven~new and iphone~seven~ old phones";
while ((hashtag = hashtagPattern.exec(text))) {
      alert(hashtag[2]); // Here we are accessing the matched hashtag
}

Answer №4

The alert gives that result because of the use of a capture group in your code.

Remember, there is no need for an extra set of parenthesis in the while loop and you don't have to escape \i in the pattern to match an i character.

By using (^|\s), any leading space will be included in the match. To avoid this, make it a non-capture group and use a separate capture group for the desired content.

You can then use console.log to view the value of group 1.

const matchHashtags2 = /(?:^|\s)(iphone~\w+)/g;
const text2 = "I have iphone~seven~new and iphone~seven~ old phones";
let hashtag2;
while (hashtag2 = matchHashtags2.exec(text2)) {
  console.log(hashtag2[1]);
}

Alternatively, you can utilize match without a capture group, along with the global flag /g preceded by a word boundary \b if that fits your matching criteria.

const matchHashtags2 = /\biphone~\w+/g;
const text2 = "I have iphone~seven~new and iphone~seven~ old phones";
console.log(text2.match(matchHashtags2));

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

Utilizing Expressjs to dynamically render views based on the status of the application

Currently, I am developing an express app that caters to two states - logged in users and anonymous users. Users are not required to log in to view the content of the site as the state is determined by the presence of a 'myapp_token' cookie. If t ...

Can you provide the Java regular expression pattern that validates the format yyyy-MM-dd hh:mm?

Struggling to validate a string in Android and having trouble finding information online. Unfortunately, I do not know how to create my own regexp. T_T In addition, I am unable to use SimpleDateFormat or other objects for this validation within an XML fil ...

Getting URL Parameters in Angular JS

How should one go about retrieving URL parameters in Angular? For instance, consider this URL: http://example.com/mypage.html?product=1234®ion=4&lang=en Thank you ...

Is it possible in React to set up a callback function for when a component is passed a specific prop, without relying on the componentwill

Instead of constantly checking for updated props in componentWillUpdate, I am looking for a more efficient way to trigger the callback only when a specific prop is updated. ...

Use the .env variable to assign the baseURL in VueAxios

I am currently utilizing a standard Vue starter webpack template with VueAxios integration. My aim is to set up axios configuration using .env variables specifically when building with the dev command. I have everything structured within the /config/index. ...

Ways to choose fresh rendered components in jQuery without the need for an event-trigger

I am currently developing a jQuery project where a specific part of the page is loaded based on different options using the load() method. Within my application, I have this line of code: $('.pe').myFunction(); The requirement is for this code ...

Exploring the Power of Functions within Angular 4 Subscriptions

I am encountering an issue when trying to call a function within a subscription. The problem arises in this function where I make a call to a subscription that refreshes a token. If the returned value is "true", I then attempt to call the same function aga ...

What is the best way to navigate to a tab on a different page using rails?

Is there a way to redirect to a specific tab on another page using Rails? I am facing an issue where clicking on a button on the first page redirects me to the default tab (basic) of the destination page. However, I would like it to redirect to the notific ...

How does JavaScript handle type conversion when the types are mismatched?

Is the right side of the operator forced to convert to the type on the left? If a number is equal to a string -> number, is it actually equal to another number? Do both sides get converted to the same underlying type, such as a number? Can a boolean ...

Lazy Loading Angular Components from a Separate Directory Beyond the App Folder

Having issues with lazy loading a module in my Angular project. Here is the current directory structure and code: I'm attempting to Lazy Load this module "tsdmns-modules/loader-module/tsdmns-loader-module.module" from "app/app-routing.module" an ...

Generate an auto-focus Power BI report seamlessly and effortlessly

I'm working on a straightforward Microsoft Power BI example that showcases a list of employees grouped by gender. <iframe width="300" height="200" src="https://app.powerbi.com/view?r=******" ></iframe> The issue I am facing is that the ...

Unable to run any npm scripts in a React project

My React application has been running smoothly for a while, but recently all the npm commands in the package.JSON file have stopped working. { "name": "fitness-appication-frontend", "version": "0.1.0", "private": true, "dependencies": { "reac ...

Is it possible for TS to recognize global variables set in Protractor configuration file?

Encountering an issue when attempting to add a global variable in the onPrepare method within the Protractor config. Typescript throws an error "Cannot find name '____'" when trying to use it in a test file. Here is how I define the global varia ...

AngularJS - Showcase a dynamic list of information according to the value chosen

Seeking assistance from anyone willing. I have data in JSON format structured like this { state1: [ member1, member2], state2: [ member3,member4...], ... } There is a dropdown that displays the states listed in the JSON data. When a state is selected, I ...

The result from Axios yields an [object Promise]

Utilizing the Flickr API, I am receiving feed images from their platform. In my Vue application, I have a computed property called filteredImages: computed: { filteredImages: async function() { return axios.get('https://api.flickr.com/services/feed ...

Using Render Callbacks in Angular Components

Is there a method to set up a callback that triggers every time the component is redrawn or re-rendered? For example, can I track how many times the component has been updated on the DOM? I have implemented OnPush change detection. @Component({ changeD ...

I created a custom function that combines two arrays into one, but I am encountering an error stating "Unable to access properties of undefined."

I am facing a challenge with combining two arrays into one new array that merges the objects of each array together. While I know how to merge two arrays into a single array, I am struggling to combine the actual objects into a brand new object within that ...

Is there a way to make the onKeyDown event function properly in Next.js/React?

I'm currently developing a website with Next.js and am facing an issue trying to execute a simple function when a key is pressed. Strangely, the onKeyDown event isn't getting triggered as expected in my code snippet: <main onKeyDown={e => c ...

Navigating through multiple layers of React refs can be achieved using a technique called travers

Hey there, I'm currently working on extracting all the a tags from within the #header-nav section. const HeaderNav = (props) => { // setState const $target = useRef(null); const $component = $target.current.querySelectorAll('a'); return ...

Getting an error message like "npm ERR! code ENOTFOUND" when trying to install Angular CLI using the command "

Currently, I am eager to learn Angular and have already installed Node version 18.13.0. However, when attempting to install Angular CLI using the command npm install -g @angular/cli, I encountered an issue: npm ERR! code ENOTFOUND' 'npm ERR! sys ...