Discovering a remedy for JavaScript Regex SyntaxError

I am encountering a syntax error while attempting to use this regular expression in my JavaScript code.

const regex = /(\w{2,}+.( ){1,})|(, \w+)/g;

Could someone please assist me in identifying the mistake?

The goal is to eliminate any titles, white spaces preceding names, and any dots or special characters from names within the string.

Example:

 DR. Tida.     =>  Tida
prof. Sina.    =>  Sina

Answer №1

you can use the regex below to achieve the desired outcome

(?<=\w+\. ?)\w+

Answer №2

Essentially, the qualifier +., + refers to one or more of the preceding characters or group causing an issue

+.( )

In an attempt to fix it, I adjusted the code to :

const regex = /(\w{2,}\.( ){1,})|(, \w+)/g;

I made modifications to your regex by using word characters, capturing them in a group, and adding optional dot checking

const regex = /^\w+[.\s]\s*|\.$/g;

const nama = "DR. Tida";
const nama1 = "prof. Sina.";
const regex = /^\w+[.\s]\s*|\.$/g;
console.log(nama.replace(regex,""));
console.log(nama1.replace(regex,""));

This flexible regex allows you to extract specific parts of a name like the first name or last name using $1 or $2

const regex = /(\w+)\.\s(\w+)(\.?)/;

const nama = "DR. Tida";
const nama1 = "prof. Sina.";

const regex = /(\w+)\.\s(\w+)(\.?)/g;
console.log(nama.replace(regex,"$2"));
console.log(nama1.replace(regex,"$2"));

Answer №3

Although Javascript does not support possessive quantifier like \w{2,}+, your pattern may not give the desired results after replacement.

Remember that a space ( ) does not need to be within parenthesis to create a group. You must escape the dot \. to match it literally, and {1,} can be represented as +.

You could repeat matching 2 or more word characters followed by a dot and 1 or more spaces OR match 1 or more non-word characters except for whitespace characters.

In the replacement, simply use an empty string.

(?:\w{2,}\.[^\S\n]+)+|[^\w\s]+

Check out this regex 101 demonstration.

const regex = /(?:\w{2,}\.[^\S\n]+)+|[^\w\s]+/g;
const s = `DR. Tida.
prof. Sina.
DR. prof. Tida.`;

console.log(s.replace(regex, ""));


Keep in mind that this part \w{2,}\. might match more than just titles.

To make it more specific, you may list what you want to remove using alternation:

(?:\b(?:DR|prof)\.[^\S\n]+)+|[^\w\s]+

Here's another demo on regex101

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

Navigating a single page application with the convenience of the back button using AJAX

I have developed a website that is designed to function without keeping any browser history, aside from the main page. This was primarily done for security reasons to ensure that the server and browser state always remain in sync. Is there a method by whi ...

How to customize TextField error color in Material-UI using conditional logic in React

Currently, I am incorporating the React Material-UI library into my project and faced with a challenge of conditionally changing the error color of a TextField. My goal is to alter the color of the helper text, border, text, and required marker to yellow ...

WARNING: Rendering error occurred - "TypeError: Unable to access 'text' property as it is undefined"

Trying to add an object to the tags array after making an axios post, but encountering an error when pushing the object. [Vue warn]: Error in render: "TypeError: Cannot read property 'text' of undefined" Why is this happening? I apologize if ...

"Creating an animated smoke effect using Three.js with a clear, see

I'm brand new to working with three.js and I'm trying to achieve a transparent background for the smoke canvas overlaying the image. Currently, the canvas is positioned behind the image as shown in the CSS below. canvas{ position: absolute; ...

What's the CSS equivalent of Java's window.pack() method?

I'm relatively new to css and I'm attempting to create a border around a <div>. My goal is for the border to be limited to the size of the elements inside the div and adjust dynamically in proportion to any new objects that may appear or di ...

Encountering limitations in accessing certain object properties with the openweathermap API

As I integrate axios into my react application to retrieve weather data from the openweathermap api, I'm encountering some issues with accessing specific properties from the JSON object returned by the API call. For instance, I can easily access data. ...

Developing with Angular.js using $http.get requests to access local APIs

I'm currently in the process of configuring a local development environment for an Angular.js application that pulls data from a remote API. However, I've encountered a roadblock with the cross-domain origin policy. The API only provides a JSON r ...

Uploading a large number of images to GCP Bucket results in a failure to connect to the oauth2 token

After writing a NodeJS upload function for Google Cloud bucket, I encountered an issue when trying to upload a larger dataset of over 3000 images. Initially, the uploading process seemed smooth, but then suddenly an error occurred and only some of the imag ...

Creating a dynamic slideshow using Jquery Ajax requests

I am looking for help with creating a slideshow using Ajax calls. I have successfully implemented it by adjusting the margin left, but now I need to approach it differently. I have a PHP array that I fetched from a database and I want to use it to display ...

Error encountered when attempting to assign a value of the original data type within the Array.reduce function

I am in the process of developing a function that takes a boolean indicator object like this: const fruits = { apple: false, banana: false, orange: false, mango: false, }; Along with an array such as ['apple', 'orange']. The go ...

I'm experiencing difficulties loading data using AJAX

I'm facing an issue with an old script that used to load IP from an xml file. Everything was running smoothly until about six months ago when I tried to use it again and encountered some problems. I'm not sure what went wrong. Could there have be ...

Revamping and Refreshing JSON-driven Pointers

My website features a jQuery code that displays live .JSON files from an ADS-B receiver with plane lat/long information. I have successfully turned them into markers, but they only update when the page is refreshed. Despite trying setInterval and conduct ...

The functionality of 'Access-Control-Allow-Origin': '*' is not operational

I attempted to address all inquiries pertaining to this tag, yet I encountered a hurdle. Where did I go wrong? $(document).ready(function () { $.ajax({ type: "GET", url: "http://www.tcmb.gov.tr/kurlar/today.xml", dataType: "xml ...

What is the best method for retrieving Json data and updating an HTML table in real time?

I am working with a Json data file that is updating every second. My goal is to display this data in real time on an HTML page of my website without having to reload the entire page. I am new to JavaScript and currently in the learning phase, so any help w ...

Verify if input is selected using jQuery

Is it possible to achieve the following using jQuery? if($(this).parent().find('input:checked') == true) {$(this).find('.switch').attr('state','on');} else{$(this).find('.switch').attr('state',& ...

Determining whether a path is absolute or relative: A step-by-step guide

Is there a universal function in node.js that can determine if a given path is absolute or relative? Unlike Windows, which starts with 'C:' or '\', UNIX paths begin with '/'. ...

Is there a way to insert a row into a datatable without needing to perform an Ajax reload or using the

When using row.add(…) on a datatable, I encounter an issue where it refreshes via an ajax call when draw() is activated. This leads to the new row not being visible because the data is reloaded from the database. The UX flow behind this scenario is as f ...

How to structure a multi-dimensional array in JavaScript

I have received JSON data displayed below. [ { "id":5, "entity_id":122, "entity_type":"STUDENT", "edit_type":"UPDATE", "created_by":122, "created_date":"2017-04-04T18:30:00.000Z", "change_log_id":2, "fiel ...

Having issues with angular-file-upload failing to include the file in the request

I am currently using angular-file-upload in order to upload an image to a server that is utilizing Node and Express 4.0. However, I am encountering difficulties in accessing the file data on the server. Below is the relevant code snippet: <input type= ...