Matching patterns with regular expressions in Javascript

There's a string that goes like this:

|Africa||Africans||African Society||Go Africa Go||Mafricano||Go Mafricano Go||West Africa|
.

I'm attempting to craft a regular expression that will only match terms containing the word Africa or any variation of it (yes to all terms above except for |Mafricano| and |Go Mafricano Go|). Each term is enclosed between two |.

Currently, I've devised: /\|[^\|]*africa[^\|]*\|/gi, which is written as follows:


  1. \| Match |

  1. [^\|]* Match zero to unlimited instances of any character except |

  1. africa Match africa literally

  1. [^\|]* Match zero to unlimited instances of any character except |

  1. \| Match |

I tried adding in ((?:\s)|(?!\w)) to make it

/\|[^\|]*((?:\s)|(?!\w))africa[^\|]*\|/gi
. While it successfully excludes |Mafricano| and |Go Mafricano Go|, it also leaves out all other entries except for |West Africa| and |Go Africa Go|. This is a step in the right direction but I need it to include all single words with Africa and its derivatives too.

Any assistance would be appreciated?

Answer №1

Try out this regular expression pattern

[^|]*\bCalifornia[a-z]*\b[^|]*

DEMO

var str = "|California||Californians||California Dreaming||Go California Go||CaliLife||West Coast|";
var arr = str.match(/[^|]*\bCalifornia[a-z]*\b[^|]*/g);
console.log(arr); // ["California", "Californians", "California Dreaming", "Go California Go", "CaliLife"] 

Answer №2

Perhaps you are looking for a solution similar to this:

\|(?:(?!Mafrica|\|).)*?africa(?:(?!Mafrica|\|).)*?\|

here is a working example

> "|Africa||Africans||African Society||Go Africa Go||Mafricano||Go Mafricano Go||West Africa|".match(/\|(?:(?!Mafrica|\|).)*?africa(?:(?!Mafrica|\|).)*?\|/gi);
[ '|Africa|',
  '|Africans|',
  '|African Society|',
  '|Go Africa Go|',
  '|West Africa|' ]

Remember to use the i modifier for case insensitive matching.

Explanation:

\|                       '|'
(?:                      group, but do not capture (0 or more
                         times):
  (?!                      look ahead to see if there is not:
    Mafrica                  'Mafrica'
   |                        OR
    \|                       '|'
  )                        end of look-ahead
  .                        any character except \n
)*?                      end of grouping
africa                   'africa'
(?:                      group, but do not capture (0 or more
                         times):
  (?!                      look ahead to see if there is not:
    Mafrica                  'Mafrica'
   |                        OR
    \|                       '|'
  )                        end of look-ahead
  .                        any character except \n
)*?                      end of grouping
\|                       '|'

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

Struggling with effectively executing chained and inner promises

It seems like my promises are not completing as expected due to incorrect handling. When using Promise.all(), the final result displayed with console.log(payload) is {}. Ideally, it should show something similar to this: { project1: { description: & ...

bringing in a nested object from an API

Check out this link: http://jsonplaceholder.typicode.com/users. In the address object, there is a geo object that I attempted to import using this method, but it doesn't display anything on the webpage. {identity.address && identity.geo & ...

Conditionally displaying ng-options in AngularJSI'm looking for a

After spending hours searching, I'm unable to find a solution to my problem. I was able to implement it before but lost the code and can't remember how I did it. I need to display only certain array values in a select box using ng-options. The d ...

Attempting to conceal image previews while incorporating pagination in Jquery

I'm working on implementing pagination at the bottom of a gallery page, allowing users to navigate between groups of thumbnail images. On this page, users can click on thumbnails on the left to view corresponding slideshows on the right. HTML <di ...

What is the best way to assign user input to my JavaScript variables?

As a newcomer to programming, I am eager to develop an app that utilizes the numerical values inputted by customers as variables for calculations. How can I extract the value from an input using JavaScript? For instance, how can I subtract one input value ...

Preventing Content Changes When Ajax Request Fails: Tips for Error Checking

I was struggling to find the right words for my question -- My issue involves a basic ajax request triggered by a checkbox that sends data to a database. I want to prevent the checkbox from changing if the ajax request fails. Currently, when the request ...

Issue with setTimeout function when used in conjunction with an ajax call

Currently, I am developing a quiz portal where questions are organized in modules. Each module consists of 5 questions: the first 4 are text-based, and the 5th is an image-based question. Upon registering through register.php, users are directed to index. ...

Sending "item" properties to the "Route" element

I am looking for a way to dynamically pass a list of route objects as props for the Route components in my AppRouter component. Currently, I have the routes defined like this: export const routes = [ { path: '/about', element: About, exact: tru ...

The combination of Masonry, FlexSlider, and endless scrolling functionality creates a

I am currently using the Masonry layout and implementing infinite scroll functionality through a jQuery plugin. Within this content, I have various FlexSlider slideshows. Unfortunately, when I trigger the infinite scroll feature, the slider does not displa ...

What could be the reason for this code not waiting for module imports?

Currently, I am facing an issue with dynamically importing modules in a nodejs server running in the development environment. To achieve this, I have implemented an immediately-invoked async function which, in theory, should work perfectly. However, it see ...

Identify when two calendar dates have been modified

Creating a financial report requires the user to select two dates, search_date1 and search_date2, in order for a monthly report to be generated. Initially, I developed a daily report with only one calendar, where I successfully implemented an AJAX script ...

What is the connection between serialization and JSON?

Can you explain serialization? Serialization is the process of converting an object into a stream of bytes, allowing it to be sent over a network or stored in a file. This allows the object to be reconstructed later on. What exactly is JSON? JSON stands ...

Updating a nested subarray using Node.js with the MongoDB API

I am currently in the process of developing a backend API using Node.js/Express and MongoDB for managing student records. I am facing difficulty with updating a sub-field within the data structure. Below is the code snippet from my Student.js file located ...

C# - Issue with Webbrowser failing to fully load pages

I am facing an issue with loading pages completely on the web browser, likely due to heavy usage of JavaScript. To address this problem, I have integrated another browser into the project called Awesomium. I am wondering if Awesomium supports using getEle ...

Tips on assigning a value to a dynamically generated drop-down element

I used arrays of strings to populate drop-down menus. Is there a way to automatically set the value of each option to match the text content? el.value = opt; seems to be ineffective. var validCoursesKeys = ['opt 1','opt 2','opt ...

Mastering the art of resolving a dynamic collection of promises with '$.all'

Imagine having 3 promises and passing them to $q.all. This results in a new promise that resolves when the 3 promises are resolved. But what if I realize before the 3 promises resolve that I also want a 4th promise to be resolved? Can this be achieved? I ...

What steps can be taken in Javascript to handle a response status code of 500?

I am currently utilizing a login form to generate and send a URL (referred to as the "full url" stored in the script below) that is expected to return a JSON object. If the login details are accurate, the backend will respond with a JSON object containing ...

In JavaScript, Identify the filename selected to be attached to the form and provide an alert message if the user chooses the incorrect file

I have a form in HTML that includes an input field for file upload. I am looking to ensure that the selected file matches the desired file name (mcust.csv). If a different file is chosen, I want to trigger a JS error. Below is the form: <form name="up ...

Issue with Bootstrap modal not closing

I've encountered an issue with a bootstrap modal popup. When I try to close the popup, it doesn't behave as expected. Instead of just hiding the popup and removing the backdrop, it hides the popup but adds another backdrop, making the screen almo ...

Can a file be imported into Node.js without the need for packaging?

Is there a way to have an entire file evaluated in node? For example, let's say I want to evaluate the angular.js source file. An example of what the code could look like is as follows: jsdom = require("jsdom").jsdom; document = jsdom("<html>& ...