views:

370

answers:

6
var string = 'abcd+1';
var pattern = 'd+1'
var reg = new RegExp(pattern,'');
alert(string.search(reg));

I found out last night that if you try and find a plus sign in a string of text with a javascript regular expression, it fails. It will not find that pattern, even though to me it looks pretty clear that is exists. This has to be because of a special character. What's the best way to find a plus sign in a piece of text? Also, what other characters will this fail on?

+11  A: 

Plus is a special character in regular expressions.

var reg = /d\+1/;
David Dorward
+1  A: 

You should use the escape character \ in front of the + in your pattern. eg. \+

Ash
Not when constructing a RegEx from a string. "\+" is the same as "+", it would have to be "\\+".
David Dorward
@David, do you mean in C# for example? In that case I normally use the @ verbatim string character to avoid too many \\\\\\ symbols ;)
Ash
@Ash: No. For example, var pattern = new RegExp("(\\d+)\\s*\\+\\s*(\\d+)"); is equivalent to var pattern = /(\d+)\s*\+\s*(\d+)/;
Anonymous
+2  A: 

You probably need to escape the plus sign:

var pattern = /d\+1/

The plus sign is used in regular expressions to indicate 1 or more characters in a row.

Kaleb Brasee
Nope, either remove your quotes around the pattern to make it a real RegExp object, or add an additional backslash before your backslash. Backslash indicates the start of an escape sequence in JavaScript strings.
JPot
+2  A: 
\-\.\/\[\]\\ **always** need escaping
\*\+\?\)\{\}\| need escaping when **not** in a character class- [a-z*+{}()?]

But if you are unsure, it does no harm to include the escape before a non-word character you are trying to match.

A digit or letter is a word character, escaping a digit refers to a previous match, escaping a letter can match an unprintable character, like a newline (\n), tab (\t) or word boundary (\b), or a a set of characters, like any word-character (\w), any non-word character (\W).

Don't escape a letter or digit unless you mean it.

kennebec
Define **non-word**. ;-)
Tomalak
@Tomalak: [^A-Za-z0-9_] https://developer.mozilla.org/En/Core_JavaScript_1.5_Guide/Regular_Expressions
Anonymous
A: 

You can use indexOf('+');

Yrgl
A: 

Just a note,

\ should be \\ in RegExp pattern string, RegExp("d\+1") will not work and Regexp(/d\+1/) will get error.

var string = 'abcd+1';
var pattern = 'd\\+1'
var reg = new RegExp(pattern,'');
alert(string.search(reg));
//3
S.Mark