Is there a version of JavaScript's String.indexOf() that allows for regular expressions?
在javascript中,是否有等效的string.indexof()在允许第二个参数的情况下,对第一个参数采用正则表达式而不是字符串?
我需要做一些像
1 | str.indexOf(/[abc]/ , i); |
和
1 | str.lastIndexOf(/[abc]/ , i); |
虽然string.search()将regexp作为参数,但它不允许我指定第二个参数!
编辑:结果发现这比我最初想象的要困难,所以我编写了一个小的测试函数来测试所有提供的解决方案…它假定已将regexindexof和regexlastindexof添加到字符串对象中。
1 2 3 4 5 6 7 8 9 | function test (str) { var i = str.length +2; while (i--) { if (str.indexOf('a',i) != str.regexIndexOf(/a/,i)) alert (['failed regexIndexOf ' , str,i , str.indexOf('a',i) , str.regexIndexOf(/a/,i)]) ; if (str.lastIndexOf('a',i) != str.regexLastIndexOf(/a/,i) ) alert (['failed regexLastIndexOf ' , str,i,str.lastIndexOf('a',i) , str.regexLastIndexOf(/a/,i)]) ; } } |
我测试如下,以确保至少对于一个字符regexp,结果与使用indexof相同
//在XES中查找a测试(xxx);测试(AXX);测试(xax);测试(测试);测试(AXA);试验(‘XAA’);测试(AAX);测试(AAA);
要从特定位置开始搜索(伪造
1 | str.slice(i).search(/re/) |
但这将得到较短字符串中的索引(在第一部分被切掉之后),因此如果不是
1 2 3 4 | function regexIndexOf(text, re, i) { var indexInSuffix = text.slice(i).search(re); return indexInSuffix < 0 ? indexInSuffix : indexInSuffix + i; } |
结合一些已经提到的方法(indexof显然相当简单),我认为这些函数将起到关键作用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | String.prototype.regexIndexOf = function(regex, startpos) { var indexOf = this.substring(startpos || 0).search(regex); return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf; } String.prototype.regexLastIndexOf = function(regex, startpos) { regex = (regex.global) ? regex : new RegExp(regex.source,"g" + (regex.ignoreCase ?"i" :"") + (regex.multiLine ?"m" :"")); if(typeof (startpos) =="undefined") { startpos = this.length; } else if(startpos < 0) { startpos = 0; } var stringToWorkWith = this.substring(0, startpos + 1); var lastIndexOf = -1; var nextStop = 0; while((result = regex.exec(stringToWorkWith)) != null) { lastIndexOf = result.index; regex.lastIndex = ++nextStop; } return lastIndexOf; } |
显然,修改内置的字符串对象会给大多数人发送红旗,但这可能是一次不那么重要的事情;只需注意它。
更新:编辑了
更新:通过本页评论中找到的所有测试,以及我自己的测试。当然,这并不意味着它是防弹的。感谢您的任何反馈。
我有一个简短的版本给你。它对我很管用!
1 2 3 | var match = str.match(/[abc]/gi); var firstIndex = str.indexOf(match[0]); var lastIndex = str.lastIndexOf(match[match.length-1]); |
如果你想要一个原型版本:
1 2 3 4 5 6 7 8 9 | String.prototype.indexOfRegex = function(regex){ var match = this.match(regex); return match ? this.indexOf(match[0]) : -1; } String.prototype.lastIndexOfRegex = function(regex){ var match = this.match(regex); return match ? this.lastIndexOf(match[match.length-1]) : -1; } |
编辑:如果要添加对FromIndex的支持
1 2 3 4 5 6 7 8 9 10 11 | String.prototype.indexOfRegex = function(regex, fromIndex){ var str = fromIndex ? this.substring(fromIndex) : this; var match = str.match(regex); return match ? str.indexOf(match[0]) + fromIndex : -1; } String.prototype.lastIndexOfRegex = function(regex, fromIndex){ var str = fromIndex ? this.substring(0, fromIndex) : this; var match = str.match(regex); return match ? str.lastIndexOf(match[match.length-1]) : -1; } |
要使用它,就这么简单:
1 2 | var firstIndex = str.indexOfRegex(/[abc]/gi); var lastIndex = str.lastIndexOfRegex(/[abc]/gi); |
用途:
1 | str.search(regex) |
请参阅此处的文档。
根据贝利的回答。主要的区别是,如果模式不匹配,这些方法返回
编辑:多亏了杰森·邦廷的回答,我有了一个主意。为什么不修改regex的
编辑:更新以通过测试用例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | String.prototype.regexIndexOf = function(re, startPos) { startPos = startPos || 0; if (!re.global) { var flags ="g" + (re.multiline?"m":"") + (re.ignoreCase?"i":""); re = new RegExp(re.source, flags); } re.lastIndex = startPos; var match = re.exec(this); if (match) return match.index; else return -1; } String.prototype.regexLastIndexOf = function(re, startPos) { startPos = startPos === undefined ? this.length : startPos; if (!re.global) { var flags ="g" + (re.multiline?"m":"") + (re.ignoreCase?"i":""); re = new RegExp(re.source, flags); } var lastSuccess = -1; for (var pos = 0; pos <= startPos; pos++) { re.lastIndex = pos; var match = re.exec(this); if (!match) break; pos = match.index; if (pos <= startPos) lastSuccess = pos; } return lastSuccess; } |
您可以使用SUBSTR。
1 | str.substr(i).match(/[abc]/); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | function reIndexOf(reIn, str, startIndex) { var re = new RegExp(reIn.source, 'g' + (reIn.ignoreCase ? 'i' : '') + (reIn.multiLine ? 'm' : '')); re.lastIndex = startIndex || 0; var res = re.exec(str); if(!res) return -1; return re.lastIndex - res[0].length; }; function reLastIndexOf(reIn, str, startIndex) { var src = /\$$/.test(reIn.source) && !/\\\$$/.test(reIn.source) ? reIn.source : reIn.source + '(?![\\S\\s]*' + reIn.source + ')'; var re = new RegExp(src, 'g' + (reIn.ignoreCase ? 'i' : '') + (reIn.multiLine ? 'm' : '')); re.lastIndex = startIndex || 0; var res = re.exec(str); if(!res) return -1; return re.lastIndex - res[0].length; }; reIndexOf(/[abc]/,"tommy can eat"); // Returns 6 reIndexOf(/[abc]/,"tommy can eat", 8); // Returns 11 reLastIndexOf(/[abc]/,"tommy can eat"); // Returns 11 |
您还可以将函数原型化到regexp对象上:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | RegExp.prototype.indexOf = function(str, startIndex) { var re = new RegExp(this.source, 'g' + (this.ignoreCase ? 'i' : '') + (this.multiLine ? 'm' : '')); re.lastIndex = startIndex || 0; var res = re.exec(str); if(!res) return -1; return re.lastIndex - res[0].length; }; RegExp.prototype.lastIndexOf = function(str, startIndex) { var src = /\$$/.test(this.source) && !/\\\$$/.test(this.source) ? this.source : this.source + '(?![\\S\\s]*' + this.source + ')'; var re = new RegExp(src, 'g' + (this.ignoreCase ? 'i' : '') + (this.multiLine ? 'm' : '')); re.lastIndex = startIndex || 0; var res = re.exec(str); if(!res) return -1; return re.lastIndex - res[0].length; }; /[abc]/.indexOf("tommy can eat"); // Returns 6 /[abc]/.indexOf("tommy can eat", 8); // Returns 11 /[abc]/.lastIndexOf("tommy can eat"); // Returns 11 |
快速解释我如何修改
它不是本机的,但您当然可以添加此功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <script type="text/javascript"> String.prototype.regexIndexOf = function( pattern, startIndex ) { startIndex = startIndex || 0; var searchResult = this.substr( startIndex ).search( pattern ); return ( -1 === searchResult ) ? -1 : searchResult + startIndex; } String.prototype.regexLastIndexOf = function( pattern, startIndex ) { startIndex = startIndex === undefined ? this.length : startIndex; var searchResult = this.substr( 0, startIndex ).reverse().regexIndexOf( pattern, 0 ); return ( -1 === searchResult ) ? -1 : this.length - ++searchResult; } String.prototype.reverse = function() { return this.split('').reverse().join(''); } // Indexes 0123456789 var str = 'caabbccdda'; alert( [ str.regexIndexOf( /[cd]/, 4 ) , str.regexLastIndexOf( /[cd]/, 4 ) , str.regexIndexOf( /[yz]/, 4 ) , str.regexLastIndexOf( /[yz]/, 4 ) , str.lastIndexOf( 'd', 4 ) , str.regexLastIndexOf( /d/, 4 ) , str.lastIndexOf( 'd' ) , str.regexLastIndexOf( /d/ ) ] ); |
我没有完全测试这些方法,但到目前为止它们似乎有效。
我还需要一个数组的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | Array.prototype.regexIndexOf = function (regex, startpos = 0) { len = this.length; for(x = startpos; x < len; x++){ if(typeof this[x] != 'undefined' && (''+this[x]).match(regex)){ return x; } } return -1; } arr = []; arr.push(null); arr.push(NaN); arr[3] = 7; arr.push('asdf'); arr.push('qwer'); arr.push(9); arr.push('...'); console.log(arr); arr.regexIndexOf(/\d/, 4); |
在所有建议的解决方案都以某种方式使我的测试失败之后,(编辑:在我写下这些解决方案之后,有些解决方案被更新为通过测试),我找到了array.indexof和array.lastindexof的Mozilla实现
我使用这些工具来实现我的string.prototype.regexindexof和string.prototype.regexlastindexof版本,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | String.prototype.regexIndexOf = function(elt /*, from*/) { var arr = this.split(''); var len = arr.length; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; for (; from < len; from++) { if (from in arr && elt.exec(arr[from]) ) return from; } return -1; }; String.prototype.regexLastIndexOf = function(elt /*, from*/) { var arr = this.split(''); var len = arr.length; var from = Number(arguments[1]); if (isNaN(from)) { from = len - 1; } else { from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; else if (from >= len) from = len - 1; } for (; from > -1; from--) { if (from in arr && elt.exec(arr[from]) ) return from; } return -1; }; |
它们似乎通过了我在问题中提供的测试功能。
显然,它们只在正则表达式与一个字符匹配时才起作用,但这对于我来说已经足够了,因为我将把它用于([abc]、s、w、d)等操作。
我将继续监视这个问题,以防有人提供更好/更快/更干净/更通用的实现,这些实现可以在任何正则表达式上工作。
在某些简单的情况下,可以使用split简化向后搜索。
1 2 3 4 | function regexlast(string,re){ var tokens=string.split(re); return (tokens.length>1)?(string.length-tokens[tokens.length-1].length):null; } |
这有一些严重的问题:
但从好的方面来说,代码要少得多。对于不能重叠的等长regex(如
仍然没有执行请求的任务的本机方法。
这是我使用的代码。它模拟了string.prototype.indexof和string.prototype.lastindexof方法的行为,但是除了表示要搜索的值的字符串之外,它们还接受regexp作为搜索参数。
是的,只要有一个答案,它就会尽可能地遵循当前的标准,当然也会包含大量的JSDoc注释。然而,一旦缩小,代码就只有2.27K,而一旦gzip用于传输,它就只有1023字节。
添加到
它通过了OP发布的所有测试,此外,我在日常使用中对这些例程进行了非常彻底的测试,并试图确保它们在多个环境中工作,但始终欢迎反馈/问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 | /*jslint maxlen:80, browser:true */ /* * Properties used by searchOf and searchLastOf implementation. */ /*property MAX_SAFE_INTEGER, abs, add, apply, call, configurable, defineProperty, enumerable, exec, floor, global, hasOwnProperty, ignoreCase, index, lastIndex, lastIndexOf, length, max, min, multiline, pow, prototype, remove, replace, searchLastOf, searchOf, source, toString, value, writable */ /* * Properties used in the testing of searchOf and searchLastOf implimentation. */ /*property appendChild, createTextNode, getElementById, indexOf, lastIndexOf, length, searchLastOf, searchOf, unshift */ (function () { 'use strict'; var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1, getNativeFlags = new RegExp('\\/([a-z]*)$', 'i'), clipDups = new RegExp('([\\s\\S])(?=[\\s\\S]*\\1)', 'g'), pToString = Object.prototype.toString, pHasOwn = Object.prototype.hasOwnProperty, stringTagRegExp; /** * Defines a new property directly on an object, or modifies an existing * property on an object, and returns the object. * * @private * @function * @param {Object} object * @param {string} property * @param {Object} descriptor * @returns {Object} * @see https://goo.gl/CZnEqg */ function $defineProperty(object, property, descriptor) { if (Object.defineProperty) { Object.defineProperty(object, property, descriptor); } else { object[property] = descriptor.value; } return object; } /** * Returns true if the operands are strictly equal with no type conversion. * * @private * @function * @param {*} a * @param {*} b * @returns {boolean} * @see http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.4 */ function $strictEqual(a, b) { return a === b; } /** * Returns true if the operand inputArg is undefined. * * @private * @function * @param {*} inputArg * @returns {boolean} */ function $isUndefined(inputArg) { return $strictEqual(typeof inputArg, 'undefined'); } /** * Provides a string representation of the supplied object in the form *"[object type]", where type is the object type. * * @private * @function * @param {*} inputArg The object for which a class string represntation * is required. * @returns {string} A string value of the form"[object type]". * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.4.2 */ function $toStringTag(inputArg) { var val; if (inputArg === null) { val = '[object Null]'; } else if ($isUndefined(inputArg)) { val = '[object Undefined]'; } else { val = pToString.call(inputArg); } return val; } /** * The string tag representation of a RegExp object. * * @private * @type {string} */ stringTagRegExp = $toStringTag(getNativeFlags); /** * Returns true if the operand inputArg is a RegExp. * * @private * @function * @param {*} inputArg * @returns {boolean} */ function $isRegExp(inputArg) { return $toStringTag(inputArg) === stringTagRegExp && pHasOwn.call(inputArg, 'ignoreCase') && typeof inputArg.ignoreCase === 'boolean' && pHasOwn.call(inputArg, 'global') && typeof inputArg.global === 'boolean' && pHasOwn.call(inputArg, 'multiline') && typeof inputArg.multiline === 'boolean' && pHasOwn.call(inputArg, 'source') && typeof inputArg.source === 'string'; } /** * The abstract operation throws an error if its argument is a value that * cannot be converted to an Object, otherwise returns the argument. * * @private * @function * @param {*} inputArg The object to be tested. * @throws {TypeError} If inputArg is null or undefined. * @returns {*} The inputArg if coercible. * @see https://goo.gl/5GcmVq */ function $requireObjectCoercible(inputArg) { var errStr; if (inputArg === null || $isUndefined(inputArg)) { errStr = 'Cannot convert argument to object: ' + inputArg; throw new TypeError(errStr); } return inputArg; } /** * The abstract operation converts its argument to a value of type string * * @private * @function * @param {*} inputArg * @returns {string} * @see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tostring */ function $toString(inputArg) { var type, val; if (inputArg === null) { val = 'null'; } else { type = typeof inputArg; if (type === 'string') { val = inputArg; } else if (type === 'undefined') { val = type; } else { if (type === 'symbol') { throw new TypeError('Cannot convert symbol to string'); } val = String(inputArg); } } return val; } /** * Returns a string only if the arguments is coercible otherwise throws an * error. * * @private * @function * @param {*} inputArg * @throws {TypeError} If inputArg is null or undefined. * @returns {string} */ function $onlyCoercibleToString(inputArg) { return $toString($requireObjectCoercible(inputArg)); } /** * The function evaluates the passed value and converts it to an integer. * * @private * @function * @param {*} inputArg The object to be converted to an integer. * @returns {number} If the target value is NaN, null or undefined, 0 is * returned. If the target value is false, 0 is returned * and if true, 1 is returned. * @see http://www.ecma-international.org/ecma-262/5.1/#sec-9.4 */ function $toInteger(inputArg) { var number = +inputArg, val = 0; if ($strictEqual(number, number)) { if (!number || number === Infinity || number === -Infinity) { val = number; } else { val = (number > 0 || -1) * Math.floor(Math.abs(number)); } } return val; } /** * Copies a regex object. Allows adding and removing native flags while * copying the regex. * * @private * @function * @param {RegExp} regex Regex to copy. * @param {Object} [options] Allows specifying native flags to add or * remove while copying the regex. * @returns {RegExp} Copy of the provided regex, possibly with modified * flags. */ function $copyRegExp(regex, options) { var flags, opts, rx; if (options !== null && typeof options === 'object') { opts = options; } else { opts = {}; } // Get native flags in use flags = getNativeFlags.exec($toString(regex))[1]; flags = $onlyCoercibleToString(flags); if (opts.add) { flags += opts.add; flags = flags.replace(clipDups, ''); } if (opts.remove) { // Would need to escape `options.remove` if this was public rx = new RegExp('[' + opts.remove + ']+', 'g'); flags = flags.replace(rx, ''); } return new RegExp(regex.source, flags); } /** * The abstract operation ToLength converts its argument to an integer * suitable for use as the length of an array-like object. * * @private * @function * @param {*} inputArg The object to be converted to a length. * @returns {number} If len <= +0 then +0 else if len is +INFINITY then * 2^53-1 else min(len, 2^53-1). * @see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength */ function $toLength(inputArg) { return Math.min(Math.max($toInteger(inputArg), 0), MAX_SAFE_INTEGER); } /** * Copies a regex object so that it is suitable for use with searchOf and * searchLastOf methods. * * @private * @function * @param {RegExp} regex Regex to copy. * @returns {RegExp} */ function $toSearchRegExp(regex) { return $copyRegExp(regex, { add: 'g', remove: 'y' }); } /** * Returns true if the operand inputArg is a member of one of the types * Undefined, Null, Boolean, Number, Symbol, or String. * * @private * @function * @param {*} inputArg * @returns {boolean} * @see https://goo.gl/W68ywJ * @see https://goo.gl/ev7881 */ function $isPrimitive(inputArg) { var type = typeof inputArg; return type === 'undefined' || inputArg === null || type === 'boolean' || type === 'string' || type === 'number' || type === 'symbol'; } /** * The abstract operation converts its argument to a value of type Object * but fixes some environment bugs. * * @private * @function * @param {*} inputArg The argument to be converted to an object. * @throws {TypeError} If inputArg is not coercible to an object. * @returns {Object} Value of inputArg as type Object. * @see http://www.ecma-international.org/ecma-262/5.1/#sec-9.9 */ function $toObject(inputArg) { var object; if ($isPrimitive($requireObjectCoercible(inputArg))) { object = Object(inputArg); } else { object = inputArg; } return object; } /** * Converts a single argument that is an array-like object or list (eg. * arguments, NodeList, DOMTokenList (used by classList), NamedNodeMap * (used by attributes property)) into a new Array() and returns it. * This is a partial implementation of the ES6 Array.from * * @private * @function * @param {Object} arrayLike * @returns {Array} */ function $toArray(arrayLike) { var object = $toObject(arrayLike), length = $toLength(object.length), array = [], index = 0; array.length = length; while (index < length) { array[index] = object[index]; index += 1; } return array; } if (!String.prototype.searchOf) { /** * This method returns the index within the calling String object of * the first occurrence of the specified value, starting the search at * fromIndex. Returns -1 if the value is not found. * * @function * @this {string} * @param {RegExp|string} regex A regular expression object or a String. * Anything else is implicitly converted to * a String. * @param {Number} [fromIndex] The location within the calling string * to start the search from. It can be any * integer. The default value is 0. If * fromIndex < 0 the entire string is * searched (same as passing 0). If * fromIndex >= str.length, the method will * return -1 unless searchValue is an empty * string in which case str.length is * returned. * @returns {Number} If successful, returns the index of the first * match of the regular expression inside the * string. Otherwise, it returns -1. */ $defineProperty(String.prototype, 'searchOf', { enumerable: false, configurable: true, writable: true, value: function (regex) { var str = $onlyCoercibleToString(this), args = $toArray(arguments), result = -1, fromIndex, match, rx; if (!$isRegExp(regex)) { return String.prototype.indexOf.apply(str, args); } if ($toLength(args.length) > 1) { fromIndex = +args[1]; if (fromIndex < 0) { fromIndex = 0; } } else { fromIndex = 0; } if (fromIndex >= $toLength(str.length)) { return result; } rx = $toSearchRegExp(regex); rx.lastIndex = fromIndex; match = rx.exec(str); if (match) { result = +match.index; } return result; } }); } if (!String.prototype.searchLastOf) { /** * This method returns the index within the calling String object of * the last occurrence of the specified value, or -1 if not found. * The calling string is searched backward, starting at fromIndex. * * @function * @this {string} * @param {RegExp|string} regex A regular expression object or a String. * Anything else is implicitly converted to * a String. * @param {Number} [fromIndex] Optional. The location within the * calling string to start the search at, * indexed from left to right. It can be * any integer. The default value is * str.length. If it is negative, it is * treated as 0. If fromIndex > str.length, * fromIndex is treated as str.length. * @returns {Number} If successful, returns the index of the first * match of the regular expression inside the * string. Otherwise, it returns -1. */ $defineProperty(String.prototype, 'searchLastOf', { enumerable: false, configurable: true, writable: true, value: function (regex) { var str = $onlyCoercibleToString(this), args = $toArray(arguments), result = -1, fromIndex, length, match, pos, rx; if (!$isRegExp(regex)) { return String.prototype.lastIndexOf.apply(str, args); } length = $toLength(str.length); if (!$strictEqual(args[1], args[1])) { fromIndex = length; } else { if ($toLength(args.length) > 1) { fromIndex = $toInteger(args[1]); } else { fromIndex = length - 1; } } if (fromIndex >= 0) { fromIndex = Math.min(fromIndex, length - 1); } else { fromIndex = length - Math.abs(fromIndex); } pos = 0; rx = $toSearchRegExp(regex); while (pos <= fromIndex) { rx.lastIndex = pos; match = rx.exec(str); if (!match) { break; } pos = +match.index; if (pos <= fromIndex) { result = pos; } pos += 1; } return result; } }); } }()); (function () { 'use strict'; /* * testing as follow to make sure that at least for one character regexp, * the result is the same as if we used indexOf */ var pre = document.getElementById('out'); function log(result) { pre.appendChild(document.createTextNode(result + ' ')); } function test(str) { var i = str.length + 2, r, a, b; while (i) { a = str.indexOf('a', i); b = str.searchOf(/a/, i); r = ['Failed', 'searchOf', str, i, a, b]; if (a === b) { r[0] = 'Passed'; } log(r); a = str.lastIndexOf('a', i); b = str.searchLastOf(/a/, i); r = ['Failed', 'searchLastOf', str, i, a, b]; if (a === b) { r[0] = 'Passed'; } log(r); i -= 1; } } /* * Look for the a among the xes */ test('xxx'); test('axx'); test('xax'); test('xxa'); test('axa'); test('xaa'); test('aax'); test('aaa'); }()); |
1 | [cc lang="javascript"] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | </P><hr><P>杰森·邦廷的最后一个指数不起作用。我的不是最优的,但它是有效的。</P>[cc lang="javascript"]//Jason Bunting's String.prototype.regexIndexOf = function(regex, startpos) { var indexOf = this.substring(startpos || 0).search(regex); return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf; } String.prototype.regexLastIndexOf = function(regex, startpos) { var lastIndex = -1; var index = this.regexIndexOf( regex ); startpos = startpos === undefined ? this.length : startpos; while ( index >= 0 && index < startpos ) { lastIndex = index; index = this.regexIndexOf( regex, index + 1 ); } return lastIndex; } |
对于稀疏匹配的数据,在浏览器中使用string.search是最快的。它在每次迭代中重新切片一个字符串,以:
1 2 3 4 5 6 7 8 9 10 11 | function lastIndexOfSearch(string, regex, index) { if(index === 0 || index) string = string.slice(0, Math.max(0,index)); var idx; var offset = -1; while ((idx = string.search(regex)) !== -1) { offset += idx + 1; string = string.slice(idx + 1); } return offset; } |
对于密集的数据,我做了这个。与Execute方法相比,它很复杂,但是对于密集的数据,它比我尝试的其他方法快2-10倍,比公认的解决方案快100倍。要点是:
执行新的regex,并返回该exec或第一个exec的结果;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | function lastIndexOfGroupSimple(string, regex, index) { if (index === 0 || index) string = string.slice(0, Math.max(0, index + 1)); regex.lastIndex = 0; var lastRegex, index flags = 'g' + (regex.multiline ? 'm' : '') + (regex.ignoreCase ? 'i' : ''), key = regex.source + '$' + flags, match = regex.exec(string); if (!match) return -1; if (lastIndexOfGroupSimple.cache === undefined) lastIndexOfGroupSimple.cache = {}; lastRegex = lastIndexOfGroupSimple.cache[key]; if (!lastRegex) lastIndexOfGroupSimple.cache[key] = lastRegex = new RegExp('.*(' + regex.source + ')(?!.*?' + regex.source + ')', flags); index = match.index; lastRegex.lastIndex = match.index; return (match = lastRegex.exec(string)) ? lastRegex.lastIndex - match[1].length : index; }; |
方法的JSPerf
我不明白考试的目的。需要regex的情况不可能与对indexOf的调用进行比较,我认为这是使该方法成为第一位的要点。为了让测试通过,使用"xxx"(?"!x)",然后调整regex的迭代方式。
好吧,因为你只是想匹配一个角色的位置,所以regex可能是杀伤力太大了。
我想你只需要找到这些字符中的第一个,而不是"先找到这些字符中的第一个"。
当然,这是一个简单的答案,但是要做你的问题规定要做的事情,尽管没有regex部分(因为你没有明确说明为什么它必须是regex)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | function mIndexOf( str , chars, offset ) { var first = -1; for( var i = 0; i < chars.length; i++ ) { var p = str.indexOf( chars[i] , offset ); if( p < first || first === -1 ) { first = p; } } return first; } String.prototype.mIndexOf = function( chars, offset ) { return mIndexOf( this, chars, offset ); # I'm really averse to monkey patching. }; mIndexOf("hello world", ['a','o','w'], 0 ); >> 4 mIndexOf("hello world", ['a'], 0 ); >> -1 mIndexOf("hello world", ['a','o','w'], 4 ); >> 4 mIndexOf("hello world", ['a','o','w'], 5 ); >> 6 mIndexOf("hello world", ['a','o','w'], 7 ); >> -1 mIndexOf("hello world", ['a','o','w','d'], 7 ); >> 10 mIndexOf("hello world", ['a','o','w','d'], 10 ); >> 10 mIndexOf("hello world", ['a','o','w','d'], 11 ); >> -1 |