简体   繁体   English

IE中的String.split

[英]String.split in IE

If I try this code in firefox it works fine 如果我在firefox中尝试此代码,则效果很好

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

The same code in IE not! IE中的相同代码不行!

 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? 在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. 问题在于您的参数称为string (全部小写),但是在尝试拆分时使用的是String (首字母大写)。 JavaScript is a case-sensitive language, string !== String . JavaScript是区分大小写的语言, 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). splitString.prototype上的函数(实际上是在字符串实例上),而不是String本身(构造函数)上的函数。

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. 附注:您不必包装正则表达式文本( /[\\-\\s]/ )在new RegExp(...)除非你周围的老的bug 问题开展工作在一些实现围绕全局标志,并将跨函数调用缓存/重用本地文字,这与split无关,因为您不使用g标志。

I don't think String object itself has a split() method. 我不认为String对象本身具有split()方法。 split() is a method of String instances: split()String实例的方法:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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