Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove punctuation from beginning and end of words in a string

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");
like image 753
cstudio Avatar asked Dec 16 '22 10:12

cstudio


2 Answers

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
like image 86
Wladimir Palant Avatar answered May 18 '23 12:05

Wladimir Palant


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();
like image 37
Joseph Silber Avatar answered May 18 '23 12:05

Joseph Silber