简体   繁体   中英

String.split in IE

If I try this code in firefox it works fine

 var words = String.split(new RegExp(/[\-\s]/));
 words // ["/[\-\s]/"]

The same code in IE not!

 var words = String.split(new RegExp(/[\-\s]/));
 words "Object doesn't support property or method 'split'"

Why? and what is the best way to fix it in IE?

Update :

The problem is that your argument is called string (all lower case), but you're using String (with an initial capital) when you're trying to split it. JavaScript is a case-sensitive language, string !== String .

So change this:

var words = String.split(new RegExp(/[\-\s]/)),

to this:

var words = string.split(new RegExp(/[\-\s]/)),
//          ^--- lower case s

Original answer :

split is a function on the String.prototype (effectively, on instances of strings), not on String itself (the constructor function).

So:

var words = "some words and hyphenated-words here".split(/[\-\s]/);
console.log(words); // ["some", "words", "and", "hyphenated", "words", "here"]

Side note: You don't have to wrap a regular expression literal ( /[\\-\\s]/ ) in new RegExp(...) unless you're working around an old bug issue in some implementations around the global flag and caching/reuse of local literals across function calls, which isn't relevant to split as you don't use the g flag with it.

I don't think String object itself has a split() method. split() is a method of String instances:

'a b c'.split(/\s/); //returns ['a', 'b', 'c']

split方法不适用于String类,而适用于类似以下的字符串:

"abc-123 def-456".split(/[\-\s]/);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM