Created
February 22, 2013 07:02
-
-
Save leizongmin/5011321 to your computer and use it in GitHub Desktop.
取子字符串的索引位置(不在引号内的)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 取子字符串的索引位置(不在引号内的) | |
* | |
* @param {String} text | |
* @param {String} subject | |
* @param {Integer} start | |
*/ | |
var textIndexOf = function (text, subject, start) { | |
if (start < 0) { | |
start = text.length + start; | |
} else if (isNaN(start)) { | |
start = 0; | |
} | |
var subjectLength = subject.length; | |
var quote = false; | |
for (var i = start, len = text.length; i < len; i++) { | |
var c = text[i]; | |
if (quote) { | |
if (c === quote && text[i - 1] !== '\\') { | |
quote = false; | |
} | |
} else { | |
if ((c === '\'' || c === '"') && text[i - 1] !== '\\') { | |
quote = c; | |
} else { | |
if (text.substr(i, subjectLength) === subject) { | |
return i; | |
} | |
} | |
} | |
} | |
return -1; | |
}; | |
console.log(textIndexOf('123456abc789100abc', 'abc')); | |
console.log(textIndexOf('123456abc789100abc', 'abc', 8)); | |
console.log(textIndexOf('123456abc789100abc', 'abc', -4)); | |
console.log(textIndexOf('123456"abc"789100abc', 'abc')); | |
console.log(textIndexOf('123456"abc\\"789100abc', 'abc')); | |
console.log(textIndexOf('123456"abc\\\'789100abc', 'abc')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment