Jumbalaya Wanton
Jumbalaya Wanton

Reputation: 1621

JS regexp to match special characters

I'm trying to find a JavaScript regexp for this string: ![](). It needs to be an exact match, though, so:

`!()[]`      // No match
hello!()[]   // No match
!()[]hello   // No Match
!()[]        // Match
 !()[]       // Match (with a whitespace before and/or after)

I tried this: \b![]()\b. It works for words, like \bhello\b, but not for those characters.

Upvotes: 2

Views: 82

Answers (4)

user1636522
user1636522

Reputation:

Let's create a function for convenience :

function find(r, s) {
    return (s.match(r) || []).slice(-1);
}

The following regular expression accepts only the searched string and whitespaces :

var r = /^\s*(!\[\]\(\))\s*$/;
find(r, '![]() ');      // ["![]()"]
find(r, '!()[] ');      // []
find(r, 'hello ![]()'); // []

This one searches a sub-string surrounded by whitespaces or string boundaries :

var r = /(?:^|\s)(!\[\]\(\))(?:\s|$)/;
find(r, '![]() ');      // ["![]()"]
find(r, 'hello ![]()'); // ["![]()"]
find(r, 'hello![]()');  // []

Upvotes: 1

rzymek
rzymek

Reputation: 9281

This matches your example:

\s*!\[\]\(\)\s*

Regular expression visualization

Though the match also includes the spaces before and after !()[].

I think \b does not work here because ![]() is not a word. Check out this quote from MDN:

\b - Matches a word boundary. A word boundary matches the position where a word character is not followed or preceeded by another word-character. Note that a matched word boundary is not included in the match. In other words, the length of a matched word boundary is zero.

Upvotes: 1

Senad Meškin
Senad Meškin

Reputation: 13756

To match all characters except letters and numbers you can use this regex

/[^A-Z0-9]/gi

g - search global [ mean whole text, not just first match ] i -case insensitive

to remove any other sign for example . and ,

/[^A-Z0-9\.\,]/gi

In order to match exact string you need to group it and global parameter

/(\!\[\]\(\))/g 

so it will search for all matches

Upvotes: 0

Hugo Tunius
Hugo Tunius

Reputation: 2879

The characters specified are control characters and need to be escaped also user \s if you want to match whitespace. Try the following

\s?!(?:\[\]\(\)|\(\)\[\])\s?

EDIT: Added a capture group to extract ![]() if needed

EDIT2: I missed that you wanted order independant for [] and () I've added it in this fiddle http://jsfiddle.net/MfFAd/3/

Upvotes: 3

Related Questions