Finding Plus Sign in Regular Expression

前端 未结 7 2301
陌清茗
陌清茗 2020-11-27 17:49
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 tr

相关标签:
7条回答
  • 2020-11-27 18:17

    It should be var pattern = '/d\\+1/'.

    The string will escape '\\' as '\' ('\\+' --> '\+') so the regex object init with /d\+1/

    0 讨论(0)
  • 2020-11-27 18:23

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

    0 讨论(0)
  • 2020-11-27 18:26
    \-\.\/\[\]\\ **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.

    0 讨论(0)
  • 2020-11-27 18:31

    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
    
    0 讨论(0)
  • 2020-11-27 18:37

    Plus is a special character in regular expressions, so to express the character as data you must escape it by prefixing it with \.

    var reg = /d\+1/;
    
    0 讨论(0)
  • 2020-11-27 18:39

    Easy way to make it :

    The alphabet is : "[\+]"

    All plus signs we want to find : "[\+]*"

    0 讨论(0)
提交回复
热议问题