views:

67

answers:

2

First question : I want to replace all characters other than alphanumeric and Special Letters. For example , somestringğüş iöç123456!@#$%^&*()_+ to somestringğüş iöç123456

Second: For example , some---example--long-string to some-example-long-string

I do not really know regexp , so I need 2 simple regexp strings.Thank you

+3  A: 
 /* 1. */   return x.replace(/[!@#$%^&*()_+]/g, '');
 /* 2. */   return x.replace(/-{2,}/g, '-');
KennyTM
I like this answer.
Multiplexer
two or more hyphens should be replaced with empty string.
SilentGhost
@Silent: Oops you're right. Fixed.
KennyTM
You were right that first time: that should be `replace(/-{2,}/g, '-')`. `some---example` --> `some-example`
Kobi
Oguz
@oguz - I don't see how that's possible, that'd change `a---b` to `ab`, not `a-b`.
Kobi
@Kobi: you're right, @Kenny: sorry, don't know what was I thinking
SilentGhost
+2  A: 

First. It matches any character that is not alphanumeric, whitespace or non-ascii, and replaced them with the empty string.

str.replace(/[^a-z0-9\s\x80-\uFFFF]+/gi, '');

There are no unicode-classes that I can use, so either I include all unicode characters, or list the ones that are not letters, digits nor whitespace.

Second. It matches any sequence of two or more dashes, and replaces them with a single dash.

str.replace(/-{2,}/g, '-');
MizardX
`ğ` and `ş` are outside of the `\x80-\xff` block.
KennyTM
Oh, right. Javascript has unicode strings.
MizardX
You can combine these replaces: `str.replace(/[^a-z0-9\s\x80-\uFFFF]+/gi, '-')`
Gumbo
@Gumbo: Not quite, because that would introduce a dash in `a###b` instead. That may be okay, of course, but that's not what's specified. It is possible to do this in one regex nonetheless, but I'm not sure if it's worth it, and I'm not sure what OP wants `a#-#-#-#b` to become (i.e. `a---b` or `a-b`?)
polygenelubricants