JavaScript split function - use of escape characters? - Stack Overflow

The following two examples do the same thing.I was wondering why Option 1 is given in a code example I

The following two examples do the same thing.

I was wondering why Option 1 is given in a code example I found and not Option 2?

What is the significance of the forward/backward slashes in '/\&/'

Option 1.

    var pairs = qString.split(/\&/);

Option 2.

    var pairs = qString.split('&');

The following two examples do the same thing.

I was wondering why Option 1 is given in a code example I found and not Option 2?

What is the significance of the forward/backward slashes in '/\&/'

Option 1.

    var pairs = qString.split(/\&/);

Option 2.

    var pairs = qString.split('&');
Share asked Mar 14, 2011 at 5:05 js_newbjs_newb 131 silver badge3 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

split() is a function that can take a regex as well as a string parameter, the forward slash usage is something called a regex literal and it is not really passing a string but a regex object.

The following statements in javascript are the same.

var regex = /\&/; // Literal
var regex = new RegExp("\\&"); // Explicit

Option 1 uses a RegEx constant which is declared with surrounding forward slashed (/).

Option 2 uses a string.

See https://developer.mozilla/en/Core_JavaScript_1.5_Guide/Regular_Expressions

The first example splits on a regular expression (constructed using the leaning-toothpick (/.../) syntax), while the second splits on a plain string.

Regular expressions are a powerful sub-language that allow plex string matching; in this case, the overhead of using one to split on a literal character (while probably negligible) is a little silly. It's like hiring a top-notch architect to build a wooden cube.

In the first example, the & character is mistakenly escaped (with the \), since it is not special in regular expressions. The regular expression engine gracefully handles that, however, and still treats it as a literal &.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745067933a4609367.html

相关推荐

  • JavaScript split function - use of escape characters? - Stack Overflow

    The following two examples do the same thing.I was wondering why Option 1 is given in a code example I

    16小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信