简体   繁体   中英

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");

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();

Replace this regex with an empty string.

/(?<=\s)[^A-Z]+?(?=\w)|(?<=\w)[^a-z]*?(?=\s|$)/gi

//Explanation:
/
(?<=\s)[^A-Z]+?(?=\w)    //Find any non-letters preceded by a space and followed by a word
|                        //OR
(?<=\w)[^a-z]*?(?=\s|$)  //Any non-letters preceded by a work and followed by a space.
/gxi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM