4

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"); 
3
  • 1
    With 'between the words' do you mean inside a word? Commented Aug 18, 2011 at 15:57
  • your example removes the puntuation insides the string also, edit your title to "Remove punctuation from string with js" or edit the example. And jQuery is for DOM manipulation, not for data manipulation Commented Aug 18, 2011 at 16:00
  • It isn't really clear what "Hello!^ there" and "Hello^! there" should be converted into. My solution will convert the former into "Hello^ there" and leave the latter untouched where as Joseph Silber's solution will do the opposite (convert the latter into "Hello^ there" while leaving the former untouched). It all depends on what "a word" is for you. Commented Aug 18, 2011 at 16:51

3 Answers 3

9

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 
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.