Regular Expression: Identify specific characters at the start or end of a string

I am in need of a regular expression (regex) that can precisely match the char set 'AB' only if it is at the beginning or end of a string, and then replace it with an empty string. It is important to note that the regex should not match parts of the char set, only the whole occurrence.

  1. For example, if the input is 'AB Some AB company name AB', the output should be 'Some AB company name'.
  2. If the input is 'Balder Storstad AB', only the 'AB' at the end should be removed, while the 'B' at the beginning should remain untouched because it is not the complete 'AB' set.

This is what I have tried so far:

name.replace(/^[\\AB]+|[\\AB]+$/g, "");

However, this regex works fine unless there is a single "A" or "B" encountered at the beginning or end of the string. For instance, with the test string 'Balder Storstad AB', both 'B' at the start and 'AB' at the end are matched, resulting in 'alder Storstad'. The intention is to ignore single 'B' or 'A' characters at the edges.

What could be wrong with my regex?

EDIT:

I would like to mention one more thing. If the test strings are: "ABrakadabra AB", "Some text hahahAB", or "ABAB text text textABAB"

The "AB" sequences in these examples should not be replaced as they are part of other words and not separate instances of "AB".

Answer №1

var rgx = /(^AB\s+)|(\s+AB$)/g;

console.log("AB Some AB company name AB".replace(rgx, ""));

console.log("Balder Storstad AB".replace(rgx, ""));

console.log("ABrakadabra AB".replace(rgx, ""));

console.log("Some text hahahAB".replace(rgx, ""));

console.log("ABAB text text textABAB".replace(rgx, ""));

Explanation :

(^AB\s+) // Looking for instances of "AB" at the beginning (^) with some spaces after it
| // Or
(\s+AB$) // Looking for instances of "AB" at the end ($) with some spaces before it

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

python regex: match the period specifically, excluding any character before it

I'm currently working with a regex pattern that looks like this: r'(?:(?<!\.|\s)[a-z]\.|(?<!\.|\s)[A-Z]\.)+' My goal is to adjust it so that it only captures the period at the end of the sentences without ...

How to extract a JavaScript object from an array using a specific field

When dealing with an array of objects, my goal is to choose the object that has the highest value in one of its fields. I understand how to select the value itself: Math.max.apply(Math, list.map(function (o) { return o.DisplayAQI; })) ... but I am unsur ...

Error: React/Express - The renderToString() function encountered an unexpected token '<'

As I work on implementing server-side rendering for my React/Express application, I have hit a snag due to a syntax error related to the use of the react-dom/server renderToString() method. In my approach, I am following a tutorial mentioned here - The sn ...

When using ng-repeat in Angular.js, an additional td is created

https://jsfiddle.net/gdrkftwm/ https://i.sstatic.net/CTi2F.jpg I have encountered a problem while creating a table from a Json object. There seems to be an extra td being generated, and I'm not sure why. I want the structure of my table to resemble ...

What is the method for sending an axios post request using the application/x-www-form-urlencoded content type?

How can I successfully send an axios post request using application/x-www-form-urlencoded? I am trying to include a refresh token in the request, but currently an empty object is being sent. However, I have verified that the token exists when checking "us ...

What is the best way to retrieve the value of the first name using Protractor?

Is there a way to store the value of the first name using a protractor script? The first name is set when the user logs in and corresponds to the name of the logged-in user. I am wondering if this can be done utilizing by.addLocator(). Here is the tag tha ...

Guide to sending a similar request as a curl command through a JavaScript file

After reviewing this Stack Overflow post titled "JavaScript post request like a form submit", I came across a similar situation. Currently, I have a curl command that performs as expected: curl -v -X POST -H "application/json" -H "Content-type: applicatio ...

How can Vue handle passing an array in this scenario?

In my code snippet, I am attempting to build a simple form builder application. The goal is to include multiple select fields in the form. I encountered a problem with passing an array into a loop. Despite my efforts, the code did not work as expected. Ho ...

Change the color of a c3js chart when it loads

I have been searching for a way to customize the color of a scatter chart's plot, and I came across an example that uses d3 code within the chart http://jsfiddle.net/ot19Lyt8/9/ onmouseover: function (d) { d3.select(d3.selectAll("circle ...

Leveraging the firebreath plugin to trigger a folder dialog, enabling asynchronous selection of folders to preserve the smooth execution of Java Script without any blocking

I need to ensure that only one folder selection dialog is open at any given time. Once the user picks a folder, an event will be triggered to notify the JavaScript of the selected folder. In order to open the dialog, I have integrated code from this gist ...

Having trouble with protractor's sendKeys function when trying to interact with md-contact-chips

Does anyone know how to set a value using sendKeys in Protractor for md-contact-chips? I attempted to use element(by.model('skills')).sendKeys('Java'); but it doesn't seem to be working. Any suggestions on how to approach this in ...

Efficiently handling multiple form submissions using a single jQuery Ajax request

I'm working on a page that has 3-4 forms within divs, and I want to submit them all with just one script. Additionally, I want to refresh the content of the specific div where the form is located. However, I'm unsure of how to specify the current ...

Tips for invoking the export function in node.js using sequelize

Need help with calling the function (search_all_user) to export in node.js using sequelize module.exports = function (sequelize, Sequelize, DataTypes) { var User = sequelize.define('user', { id: {type: Sequelize.INTEGER, unique: true, prima ...

Struggling with the nested array of objects

I have utilized Mongodb aggregation and used the $facet operator to count each value of "reli" and "prov" from the collection. Here is the code I used to retrieve results from the database: const keyy = await db.aggregate([ $facet: { "reli": [ { $group ...

Replacing jQuery.ajax from a different directory/domain - problem with using relative URLs

We are incorporating scripts from various sources and domains, including one that contains the definition for jQuery.ajax function. Calls to jQuery.ajax are being made from different places and domains using relative URLs, such as jQuery.ajax("my/relativ ...

Display a PDF file within an IFrame using JavaScript and then print it

Why is it so challenging to achieve? I've dedicated 48 hours to research this, yet it seems impossible! Although recent Chrome versions allow the parent window to access PDFs in iframes, both FF and IE prevent any interaction with the iframe that dis ...

How do I control the opening and closing of my modal using redux state management?

When the user clicks on Checkout within the <CheckoutButton/> component below, the modal should appear. However, instead of this behavior, the modal is appearing when I reload my browser, which is not the expected outcome. What could be causing this ...

What might be causing the ng-model in this plunkr to not update as expected?

I recently customized a ui-select plunkr to suit my specific needs. I've noticed that the ng-model is not updating as expected, but interestingly, clicking the button to update the model results in the ui-select getting updated. Any guidance on resol ...

What could be the reason behind the ajax call not getting triggered?

Upon page load, the first alert is displaying correctly. However, the alert inside the ajax call is not triggering. It appears that the ajax call itself is not functioning as intended - it is supposed to invoke a method in the controller, but no longer s ...

Transferring information between two components in separate Angular 4 modules

Within my application, I have defined two modules named AppModule and UserModule. I am currently encountering an issue with data sharing between the AppComponent and the LoginComponent (which belongs to the UserModule). Below is a snippet of app.componen ...