I've recently discussed with a colleague how the separator of String.split is treated internally by JavaScript.

Is the separator always converted into a regular expression? E.g. will calling String.split(",", myvar) convert the "," into a regualar expression matching that string?

有帮助吗?

解决方案

Well the answer for your question: "Is the separator always converted into a regular expression?" is:

It depends solely on the implementation. For example if you look at WebKit implementation http://svn.webkit.org/repository/webkit/trunk/Source/JavaScriptCore/runtime/StringPrototype.cpp (find stringProtoFuncSplit) then you see it is not always converted to RegEx. However, this does not imply anything, it is just a matter of implementation

其他提示

Here's the official writeup over at ecma, but the relevant part is around this section:

8.If separator is a RegExp object (its [[Class]] is "RegExp"), let R = separator; otherwise let R = ToString(separator).

That being said it is the ecma spec, and as Anthony Grist mentioned in the comments, browsers can implement as they want, for instance V8 implements ecma262.

Edit: expanded thought on browser/js engines implementation, it appears the majority implement versions of ecma, as seen on this wiki

Yes, the javascript function split allow you to use regex: EX:

var str = "I am confused";
str.split(/\s/g)

Str then contains ["I","am","confused"]

separator specifies the character(s) to use for separating the string. The separator is treated as a string or a regular expression. If separator is omitted, the array returned contains one element consisting of the entire string. If separator is an empty string, str is converted to an array of characters.

Please see the below link to know more about this, hope it will help you:

String.prototype.split()

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top