I have a string and I want to remove any - ,( ,) ,& ,$ ,# ,! ,[ ,] ,{ ,} ," ,'
from the beginning or end of the word. If it is between the words just ignore those.
Here is an example:
var $string = "Hello I am a string, and I am called Jack-Tack!. My -mom is Darlean.";
I want the above text to be like this after a regex:
console.log("Hello I am a string and I am called Jack-Tack My mom is Darlean");
You can use the fact that \b
in regular expressions always matches at a word boundary whereas \B
matches only where there isn't a word boundary. What you want is removing this set of characters only when there is a word boundary on one side of it but not on the other. This regular expression should do:
var str = "Hello I'm a string, and I am called Jack-Tack!. My -mom is Darlean.";
str = str.replace(/\b[-.,()&$#!\[\]{}"']+\B|\B[-.,()&$#!\[\]{}"']+\b/g, "");
console.log(str); // Hello I'm a string and I am called Jack-Tack My mom is Darlean
Here's one I just created. It could probably be simplified, but it works.
"Hello I am a string, and I am called Jack-Tack!. My -mom is Darlean."
.replace(/(?:[\(\)\-&$#!\[\]{}\"\',\.]+(?:\s|$)|(?:^|\s)[\(\)\-&$#!\[\]{}\"\',\.]+)/g, ' ')
.trim();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With