3

I'm using the following line of PHP to remove punctuation from strings:

$key = preg_replace("/\p{P}/u", "", $key);

Does anyone know how to do the same thing in Javascript/jQuery?

I know you can use jQuery's replace() like PHP's preg_replace(). I just don't know what regular expression to use.

liz
  • 830
  • 14
  • 32
  • did you read this question? http://stackoverflow.com/questions/4328500/how-can-i-strip-all-punctuation-from-a-string-in-javascript-using-regex – Decker W Brower Aug 02 '12 at 00:03
  • 1
    javascript doesn't have expression for punctation. this may help http://stackoverflow.com/questions/7576945/javascript-regular-expression-for-punctuation-international – mask8 Aug 02 '12 at 00:05
  • @Decker - i need to make sure the expressions match exactly the same. i think the second answer on there might work for me. thanks. – liz Aug 02 '12 at 00:29

2 Answers2

1

Something like this :

<script type="text/javascript">
  var str = "Some text here ...";
  var pattern = /\p{P}/u;
  document.write(str.replace(pattern,''));
</script>

Edit :

It seems that Javascript is not PECL compatible, so the p{P} will not work.

Oussama Jilal
  • 7,669
  • 2
  • 30
  • 53
  • JavaScript regexes do not support `\p`. – alex Aug 02 '12 at 00:06
  • It seems that, as the others stated, javascript is not pecl compatible, so this will not work. You can replace all non alphanumeric caracters but that may not give you the desired result – Oussama Jilal Aug 02 '12 at 00:33
  • i think that's what all end up doing. that way i know php and javascript will produce the same results. Thanks! – liz Aug 02 '12 at 01:08
0

In most cases the regular expressions will be the same in Javascript and in PHP. So, if yo have a regexp that works in PHP it's most likely going to work the same way in JS. The main difference is that in JS you don't need to wrap (though you can if you want to) the regexp in a quotes. You can just call replace on the String directly like so...

myString.replace(/abc/i, "123");

Keep in mind that this doesn't actually alter the value of myString... it just returns the replaced version.

Yevgeny Simkin
  • 27,946
  • 39
  • 137
  • 236
  • To get the actual behaviour of `\pP`, you'll need to use a bunch of Unicode ranges. – alex Aug 02 '12 at 00:06
  • @alex, interesting... I'm not familiar with that command... entirely possible that my answer is completely useless for this particular example. – Yevgeny Simkin Aug 02 '12 at 00:08