I get a syntax error when using this regex in my JavaScript code.
const regex = /(\w{2,} .( ){1,})|(, \w )/g;
Can anyone please help me find the mistake?
My purpose is to remove any kind of title and white spaces before the names along with any dots or special characters from names in the string.
Exp:
DR. Tida. => Tida
prof. Sina. => Sina
CodePudding user response:
the following regex would work
(?<=\w \. ?)\w
CodePudding user response:
So basically ., is a qualifier that actually for one or more of the preceding characters or group which is making an issue
.( )
I tried to change it to make it run :
const regex = /(\w{2,}\.( ){1,})|(, \w )/g;
I tried to modify your regex, simply by using word characters and capturing them in a group and added optional checking on dot
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,""));
Just mentioning flexible regex where you can use the group as if you want the first name of the last name by 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"));
CodePudding user response:
Javascript does not support possessive quantifier like \w{2,}
but apart from that your pattern will not give you the desired results after replacing.
Note that the space ( )
does not have to be between parenthesis to make it a group, you have to escape the dot \.
to match it literally and {1,}
can be written as
What you might do is repeat matching 2 or more word characters followed by a dot and 1 spaces OR match 1 or more times a non word character except for a whitespace char.
In the replacement use an empty string.
(?:\w{2,}\.[^\S\n] ) |[^\w\s]
See a regex 101 demo.
const regex = /(?:\w{2,}\.[^\S\n] ) |[^\w\s] /g;
const s = `DR. Tida.
prof. Sina.
DR. prof. Tida.`;
console.log(s.replace(regex, ""));
Although this part \w{2,}\.
can obviously match more than just titles.
You can also list using an alternation what you want to remove to make it more specific:
(?:\b(?:DR|prof)\.[^\S\n] ) |[^\w\s]
See another regex101 demo