Regular expression for punctuation and text enhancement

I am trying to avoid bad behavior in our application and I need to clear a string from misuse.

Let him say that I have this line

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

      

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

So my line should be

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

      

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

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

      

But it doesn't help me remove the space before punctuation

It would be very helpful to help find the correct Regex

+3


source to share


1 answer


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:



For a scenario that uses decimal points (like in the case of - 'This is 14.5 degree'

), using a Negative lookahead (like - (?!\d+)

) should work.

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"

      

+5


source







All Articles