Mastering JavaScript Regular Expressions: Eliminating White Spaces Surrounding Specific Characters

It seems that I may be making a mistake as I found regex patterns to achieve the desired replacement in PHP and C#, but when trying to apply it in JavaScript, it is not working.

For example:

text ( 4 |-4 | 1 "test"  )  [ 0 50 90 ]

After cleaning, it should look like this:

text(4|-4|1 "test")[0 50 90]

In essence, I am aiming to remove all white spaces before and after brackets and the | symbol.

My current code attempts are:

        // remove whitespaces around brackets []
        text = text.replace(/\s*\[\s*(.*?)\s*]\s*/g, '[$1]');
        // remove whitespaces around brackets ()
        text = text.replace(/\s*\(\s*(.*?)\s*\)\s*/g, '($1)');
        // remove all whitespaces around | (unsuccessful attempt)
        // text = text.replace(/\s*\|\s*(.*?)\s*\|\s*/g, '|$1|');
        // text = text.replace(/\s*|\s*/, '$1');

This approach seems overly complex.

I would appreciate assistance in identifying the regex pattern for each symbol individually.

Instead of combining all replacements into one regex pattern, I prefer to learn by having one replacement per line.

Answer №1

Here is a solution that will work:

var sentence = 'text ( 4 |-4 | 1 "test"  )  [ 0 50 90 ]';
sentence = sentence.replace(/\s*([|()[\]])\s*/g, '$1');

alert(sentence)

The above regex code searches for optional whitespace followed by certain characters in a capture group without any surrounding spaces, and then replaces the entire match with just the character, effectively eliminating the whitespace.


If you need to place each replacement on a separate line and only remove space characters while leaving other types of whitespace intact, you can try this approach:

var phrase = 'text ( 4 |-4 | 1 "test"  )  [ 0 50 90 ]';
phrase = phrase.replace(/ *([|]) */g, '$1')
               .replace(/ *([(]) */g, '$1')
               .replace(/ *([)]) */g, '$1')
               .replace(/ *([[]) */g, '$1')
               .replace(/ *([\]]) */g, '$1');

alert(phrase)

Alternatively, you can use a simpler version like this:

var text = 'text ( 4 |-4 | 1 "test"  )  [ 0 50 90 ]';
text = text.replace(/ *(|) */g, '$1')
           .replace(/ *(\() */g, '$1')
           .replace(/ *(\)) */g, '$1')
           .replace(/ *(\[) */g, '$1')
           .replace(/ *(\]) */g, '$1');

alert(text)

For single characters, using character classes might be unnecessary, but make sure to escape ()[] as shown in the last snippet.

Answer №2

To efficiently handle reserved characters, it is essential to escape them correctly. For instance, converting a single [ to \[ and so forth. The pipe symbol is another reserved character that requires the same treatment:

let sentence = "word ( 6 |-6 | 3 \"example\" ) [ 8 20 45 ]";
    sentence = sentence.replace(/\s*([\(\)])\s*/g, '$1')); // eliminates the ()
    sentence = sentence.replace(/\s*([\[\]])\s*/g, '$1')); // eliminates the []
    sentence = sentence.replace(/\s*([\|])\s*/g, '$1'));   // eliminates the |

    // alternatively, remove all characters simultaneously
    sentence = sentence.replace(/\s*([\(\)\[\]\|])\s*/g, '$1')

alert(sentence)

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

Reverse the order of images in jQuery image slider

Hey there, I have created a simple image slider using jQuery with previous and next buttons. The slider moves automatically and the next button works fine, but I am facing some issues with the previous button. To take a look at the code and test it out you ...

What is the recommended way to select a checkbox using JQuery?

I have exhausted all options and nothing seems to be working. This is the checkbox in question: <input type="checkbox" onchange="WriteFormSelections('SearchForm', 'AccommodationType', 'AccommodationTypeSelections', 'A ...

A simple way to display a div when clicking on an anchor tag

I am in the process of developing a bus booking website that features multiple bus operators. Each bus operator is listed with a "Book Now" link, which should display specific bus information directly below the corresponding row when clicked. You can revie ...

Performing a MySQL query to select multiple rows and fields with the AND operator simultaneously

I've got a table: + --------------------------+---------------------------+--------------+--------+ | ID | SKU_ID | DKEY | DVAL | + --------------------------+---------------------------+----------- ...

Does anyone know the ins and outs of how the website www.nikebetterworld.com was created?

Hello, I am new to web development and I am interested in creating a page similar to the style of nikebetterworld. Can you point me in the right direction on where to start studying to achieve this design? My impression is that it involves multiple scrol ...

Retrieve the content within a div tag

Hey there, I have a div set up as follows: <div>1+1</div> I'm looking to send this '1+1' value over to my javascript code and calculate it to get '2'. Appreciate any help in advance! ...

What is the best method for effectively organizing and storing DOM elements alongside their related objects?

In order to efficiently handle key input events for multiple textareas on the page, I have decided to create a TextareaState object to cache information related to each textarea. This includes data such as whether changes have been made and the previous co ...

Does aoMap function exclusively with THREE.BufferGeometry?

Can you provide guidance on setting up an aoMap for a standard THREE.Geometry object? Is there a demo available to reference? var uvCoordinates = geometry.attributes.uv.array; geometry.addAttribute('uv2', new THREE.BufferAttribute(uvCoordina ...

Unable to reference a property or method in Vue.js and Vuetify due to an issue with the <v-btn-toggle> button causing an error

Just started using vuetify and exploring the <v-btn-toggle> component for the first time. I'm trying to implement a toggle feature to filter my user list based on employee, manager, or admin types... Check out a snippet of my code below: <v ...

How can I display data in jQuery FullCalendar without refreshing the page following an AJAX request?

I am currently working on integrating jQuery FullCalendar with PHP and MySQL. The issue I am facing is that when I insert a new event by selecting day(s) using AJAX, I am unsure how to display this newly added event without refreshing the page. Below is th ...

P5.js requires manual clearing of the canvas due to its unique design

When working in P5.js, I notice that any shape I draw seems to leave a faint trail as it moves. For example, when drawing an ellipsehttps://i.sstatic.net/C61YO.png Here's the code I used for testing purposes: function draw() { if (times < 100 ...

What is the best way to invoke one method from another method within the same Angular (Typescript) Component Class?

There seems to be a puzzling error occurring when attempting to call one method from another within the same Angular 2 TypeScript component. In the code snippet below, the ngOnInit() function triggers method1, which then tries to invoke this.method2(). Ho ...

I'm having trouble locating the source of the popstate loop that is generating numerous history entries

I am currently working on a project to create a dynamic webpage where the content of the main div gets replaced when certain navigation links are clicked. I have successfully implemented the pushstate function to update the div content and change the URL a ...

What is the reason for Jest attempting to resolve all components in my index.ts file?

Having a bit of trouble while using Jest (with Enzyme) to test my Typescript-React project due to an issue with an alias module. The module is being found correctly, but I believe the problem may lie in the structure of one of my files. In my jest.config ...

AngularJS/Restangular index-based extraction of JSON data

I have developed an application that takes input for quotes (purity, weight, total) and stores it in the $scope.quote array: // Controller action // $scope.quote.push({ total: ((($scope.karat * $scope.spot) * $scope.percentage) / 20) * $scope.estimated ...

Using axios to make a request from a server to itself

I'm facing an issue where I am attempting to send a request from the server to the same server using axios as a PUT method. Here is an example of what I have tried: await axios({ url: `http://localhost:4000${url}`, method: requestType, ...

Transfer vertices into a texture and send it to the shader for processing

Finally found some time to experiment with shaders, but I hit a roadblock. My goal is to pass vertices to a shader and perform general-purpose computing on them. It seems like the gpgpu functionality is working fine because I can see a few pixels being sh ...

Is the file corrupt using node.js?

Looking for ways to determine if a file is corrupted using node.js? I have attempted various File System methods, such as fs.readFile, fs.open, and fs.access, but all of them are showing an OK status. However, I am confident that my file is corrupted base ...

What causes my Bootstrap 5 popover to no longer open on focus when I reopen the modal it is attached to?

I am facing an issue with my Bootstrap 5 modal and the popovers that are attached to it. On hovering over a button in my HTML, a popover appears asking 'Are you sure?' and instructing the user to click the button to proceed. Clicking the button ...

What are the top methods for interacting between Server APIs and Client-Side JavaScript?

Presently, I am utilizing setTimeout() to pause a for loop on a vast list in order to apply some styling to the page. For example, For example: How I utilize setTimeOut: I use setTimeout() to add images, text and css progress bars (Why doesn't Prog ...