Avoiding white spaces in regular expressions in JavaScript

Below is my JavaScript code used to eliminate spaces in specific words (ستاک ئەڤەفلۆو) within a given text. When testing this code in Console.log, I encountered an issue.

var text = "ئایا ستاک ئەڤەفلۆو مانای چییە؟ دووبارە ستاک ئەڤەفلۆو مانای چییە؟";

text = text.replace(
            new RegExp("(^|\\s|_|«|»|\\[|\\(|\\<|\\>|\\')(ستاک ئەڤەفلۆو)(?= |«|»|\\.|،|_|\\]|\\s|\\:|\\)|\\<|\\>|؟|\\'|\\!|$)", 'g'),
            function (x) { return x.replace(/ /gi, ''); } // 'i' is just to deceive the bidi algorithm on the code view
        );

The output produced is incorrect:

ئایاستاکئەڤەفلۆو مانای چییە؟ دووبارەستاکئەڤەفلۆو مانای چییە؟

This result removes the space before the specified string, causing it to merge with the previous word.

The desired output should be:

ئایا ستاکئەڤەفلۆو مانای چییە؟ دووبارە ستاکئەڤەفلۆو مانای چییە؟

Thank you!

Answer №1

To enhance the code, I recommend consolidating single character alternatives into character classes and resolving the issue by eliminating spaces in Group 2 exclusively, not in Group 1.

var text = "ئایا ستاک ئەڤەفلۆو مانای چییە؟ دووبارە ستاک ئەڤەفلۆو مانای چییە؟";

text = text.replace(
  new RegExp("(^|[\\s_«»[(<>'])(ستاک ئەڤەفلۆو)(?=[«».،_\\]\\s:)<>؟'!]|$)", 'g'),
  function (x, punct, word) { return (punct || "") + word.replace(/\s+/gi, ''); }
);
console.log(text)

The regex expression breaks down as follows:

  • (^|[\s_«»[(<>']) - Capturing group 1 (punct in replacement callback): start of string or a whitespace, underscore, «, », [, (, <, >, or '
  • (ستاک ئەڤەفلۆو) - Capturing group 2 (word): specific phrase
  • (?=[«».،_\]\s:)<>؟'!]|$)
    - positive lookahead matching characters following the phrase, such as «, », ., ،, _, ], whitespace, :, ), <, >, ؟, ', !, or end of line.

When a match occurs, any matched punctuation is concatenated with the trimmed word (using word.replace(/\s+/gi, '') to remove whitespaces).

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

Guide on changing query using Ajax and Laravel when clicking a link

I am currently facing a challenging issue that seems unsolvable (I'm struggling to even understand where to begin). I have a total of four hyperlinks: https://i.sstatic.net/kn5vx.png When landing on the page initially, all the links are displayed b ...

Requesting data from a server using jQuery's AJAX functionality

Currently, I am utilizing the following piece of code for an ajax call: $('#filter').submit(function(){ var filter = $('#filter'); $.ajax({ url:filter.attr('action'), data:filter.serialize(), // form ...

The process of incorporating types into Node.js and TypeScript for handling req and res objects

Check out the repository for my project at https://github.com/Shahidkhan0786/kharidLoapp Within the project, the @types folder contains a file named (express.d.ts) where I have added some types in response. The (express.d.ts) file within the @types folde ...

Guide to Displaying Items in Order, Concealing Them, and Looping in jQuery

I am trying to create a unique animation where three lines of text appear in succession, then hide, and then reappear in succession. I have successfully split the lines into span tags to make them appear one after the other. However, I am struggling to fin ...

Leveraging Parse methods within a Node JS Cron job

My current task involves writing a Cron Job that requires the use of Parse methods. I have the following code snippet at hand: var crontab = require('node-crontab'); var jobId = crontab.scheduleJob("* * * * * *", function(){ ...

Embedded Javascript fails to function following an async postback triggered by an UpdatePanel

After embedding some JavaScript files in a server control, everything works fine. However, when the server control is placed within an ajax UpdatePanel, it ceases to function after an async postback triggered within the updatepanel. This is the code in th ...

Utilize HTTPS and HTTP with Express framework in node.js

Currently, I am utilizing the express (3.0) framework on node.js to handle routing in my application. While most of the application makes use of the http protocol, there is a specific route that I intend to serve exclusively via https. This particular par ...

React strict mode and Material UI console notifications

Just like a rapidly growing application can make the console as dirty as a footballer's shirt. What am I trying to convey? When using Material UI in strict mode, warnings such as FindDomNode may appear, or it may ask you to use strings instead of bo ...

Insert a scrollbar into the new popup window on Internet Explorer after the window has been opened

I am looking to enable scrolling in a pop-up window after it has been opened. While FireFox offers the 'window.scrollbars' property for this, Internet Explorer does not have a similar feature. Is there a way to add scrolling functionality in IE u ...

Winning opportunities created by using credits in the slot machine

**Greetings, I have created a slot machine using JavaScript, but I am looking to enhance the player's chances based on their credits. Can anyone guide me on how to achieve this? Essentially, I want the player's odds to increase proportionally wit ...

Convert alias query strings into parameters

I am currently working on a project that involves using node, express, and jade. I need to be able to access content through two different URLs: /Page/foo/bar and /Page?Foo=foo&Bar=bar The goal is for the top URL to act as an alias for the bottom o ...

How can I stop the setinterval function in JavaScript?

My issue revolves around intervals. Upon declaring a function with setInterval, I find that even after clearing the interval, the function continues to execute. Here is my code: if (score == 1) { leftBlinkTimer(0) } else if (score == 0) { leftBlin ...

Identifying selected shapes in CSS/Javascript by outlining them with small rectangles placed on each corner

Currently, I am working on a University Project that involves creating a selection function for drawn shapes such as rectangles, circles, lines, or triangles. The challenge lies in figuring out the visualization of the selection when a shape is clicked. T ...

Tips for linking weight scale device to a website

I recently developed a web application that calculates the weight of products. The application was created using PHP, JavaScript, and AJAX, running on a XAMPP server. Now my client is requesting for me to integrate a weight scale machine into the applica ...

Looking for a solution to dynamically fill a list in JQuery with data from a JSON file. Any suggestions for troubleshooting?

Currently, I am utilizing a JSON file to fetch Quiz questions. In my approach, each question is being stored in an array as an object. The structure of the question object includes 'text' (the actual question), 'choices' (an array of po ...

Dayjs is failing to retrieve the current system time

Hey everyone, I'm facing an issue with using Dayjs() and format to retrieve the current time in a specific format while running my Cypress tests. Despite using the correct code, I keep getting an old timestamp as the output: const presentDateTime = da ...

Converting Date Format According to Visitor's Time Zone in VueJs/JS

I have a Date in string Format: 2020-07-13 7:07 AM (which is indian time). I am looking to adjust this time according to the browser's time zone, which could be either in the US or Africa. I have attempted various methods to convert it accurately. He ...

Matching the scope property in AngularJS directives

I am currently working on creating a custom directive that will perform regex validation on specific input fields. The goal is for the directive to determine which regex pattern to use based on an attribute provided in the input element. Here is an exampl ...

React - Issue with Input event handling when utilizing both onChange and onKeyDown functions

I was attempting to create a feature similar to a multi-select, where users could either choose a value from a list or enter a new value. The selected value should be added to an array when the user presses the enter key. To monitor changes in the input ...

Create a file object using content with the help of JavaScript

I am working with a file containing specific data const ics = 'BEGIN:VCALENDAR\n' + 'VERSION:2.0\n' + 'CALSCALE:GREGORIAN\n' + 'METHOD:PUBLISH\n' + 'END:VCALENDAR\n'; I am trying t ...