Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to deal with punctuation and text improvement

I'm trying to avoid bad behavior on our app, and it needs me to clean some string from bad usage.

Let's says I have this string

str = "This is a very bad BEHAVIOR !!!Don't you think So ????";

I need to apply 3 rules : - no shout mode (not all CAPS) - Remove space before punctuation, and add one space after - Remove all duplicate punctuation

So my string should be

str = "This is a very bad behavior! Don't you think so?"

I found on stackoverflow a sample code to add one space after punctuation :

str.replace(/[,.!?:;](?=\S)/g, '$& ');

But that does not help me to remove space before punctuation

Help would be really appreciate to find the right Regex

like image 947
Toucouleur Avatar asked Nov 24 '25 07:11

Toucouleur


1 Answers

This seems to work -

str.replace(/\s*([,.!?:;])[,.!?:;]*\s*/g,'$1 ').  //This removes all the punctuations
replace(/(?:^|[^a-z])([A-Z]+)(?:[^a-z]|$)/g,function(v){return v.toLowerCase();}). //Upper case to lower case
replace(/\s*$/,"") //Trimming the right end

OUTPUT:
"This is a very bad behavior! Don't you think So?"

EDIT:

Regarding the scenario where decimal points are used (like in case - 'This is 14.5 degree'), using a Negative lookahead(like so - (?!\d+) ) should work.

For Example -

str = 'This is 14.5 degree'
str.replace(/\s*(?!\d+)([,.!?:;])[,.!?:;]*(?!\d+)\s*/g,'$1 ').  //This removes all the punctuations
replace(/(?:^|[^a-z])([A-Z]+)(?:[^a-z]|$)/g,function(v){return v.toLowerCase();}). //Upper case to lower case
replace(/\s*$/,"") //Trimming the right end

OUTPUT:
"This is 14.5 degree"
like image 155
Kamehameha Avatar answered Nov 25 '25 20:11

Kamehameha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!