Click here to Skip to main content
15,845,436 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to save Excel data to the database but the problem is before inserting it into the database remove all the commas, dots and spaces from the string.By using Regex i want a function which can give me below output.

for example :-1.string contains P G it saves PG or P,. G returns PG
2. if the string is Workshop Related Expenses the output is same in that case i dont want remove spaces.

if the string is single then remove spaces, commas and dots but when it is sentence remove commas and dots.

What I have tried:

function convertString(d) {
        if (typeof d === "string") {
          let regex = /[^a-zA-Z ]/g;
          let newString= d.replace(regex, "");
          d = newString;
        }
        return d;
      }
Posted
Updated 18-Apr-23 21:11pm
v2

1 solution

Your regex excludes spaces, and includes all punctuation as well as numeric characters. To remove commas, dots, and spaces is easy:
RegEx
[\.,\s]
But ... you will have to work out rules for you second requirement fairly carefully - when does a space get removed? Is it "not after a word of sufficient length"? Or "not between two words of sufficient length"? What about "I am a human"? Should that remain as it is, or have some or all spaces removed? What about "I, a human ..."?

I suspect that you are going to stress Regexes too far to get maintainable code and meaningful results, and that you will need to define your problem to yourself a load better before you even try to sort this - with or without a Regex!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900