답변:
const string = "XYZ 123 ABC 456 ABC 789 ABC";
function getPosition(string, subString, index) {
return string.split(subString, index).join(subString).length;
}
console.log(
getPosition(string, 'ABC', 2) // --> 16
)
fromIndex에 인수String.indexOf
function getPosition(str, m, i) { return str.split(m, i).join(m).length; }
i발생하는 경우 문자열의 길이를 제공합니다 m. 즉, getPosition("aaaa","a",5)제공 4등의 수행, getPosition("aaaa","a",72)! 이 경우 -1을 원한다고 생각합니다. var ret = str.split(m, i).join(m).length; return ret >= str.length ? -1 : ret;또한 캐치 될 가능성 i <= 0에return ret >= str.length || i <= 0 ? -1 : ret;
배열을 만들지 않고 indexOf 문자열을 사용할 수도 있습니다.
두 번째 매개 변수는 다음 일치 항목을 찾기 시작하는 색인입니다.
function nthIndex(str, pat, n){
var L= str.length, i= -1;
while(n-- && i++<L){
i= str.indexOf(pat, i);
if (i < 0) break;
}
return i;
}
var s= "XYZ 123 ABC 456 ABC 789 ABC";
nthIndex(s,'ABC',3)
/* returned value: (Number)
24
*/
i덜 혼란스럽게 만들 수 있습니다.var i; for (i = 0; n > 0 && i !== -1; n -= 1) { i = str.indexOf(pat, /* fromIndex */ i ? (i + 1) : i); } return i;
kennebec의 답변을 바탕으로 n 번째 발생이 0이 아닌 -1을 반환하는 프로토 타입 함수를 만들었습니다.
String.prototype.nthIndexOf = function(pattern, n) {
var i = -1;
while (n-- && i++ < this.length) {
i = this.indexOf(pattern, i);
if (i < 0) break;
}
return i;
}
String.prototype.nth_index_of.. 당신이 당신의 이름이 독특하고 충분히 미쳤다고 생각하더라도 세상은 그것이 더 미쳤을 수 있고 할 것임을 증명할 것입니다.
INSERTmysqli_real_escape_string
재귀가 항상 답이기 때문입니다.
function getPosition(input, search, nth, curr, cnt) {
curr = curr || 0;
cnt = cnt || 0;
var index = input.indexOf(search);
if (curr === nth) {
if (~index) {
return cnt;
}
else {
return -1;
}
}
else {
if (~index) {
return getPosition(input.slice(index + search.length),
search,
nth,
++curr,
cnt + index + search.length);
}
else {
return -1;
}
}
}
~:) 비트 단위 자바 스크립트에서 NOT 연산자입니다 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/...
다음은 n일치 항목이 발견 될 때까지 문자열을 반복하는 솔루션입니다 .
String.prototype.nthIndexOf = function(searchElement, n, fromElement) {
n = n || 0;
fromElement = fromElement || 0;
while (n > 0) {
fromElement = this.indexOf(searchElement, fromElement);
if (fromElement < 0) {
return -1;
}
--n;
++fromElement;
}
return fromElement - 1;
};
var string = "XYZ 123 ABC 456 ABC 789 ABC";
console.log(string.nthIndexOf('ABC', 2));
>> 16
이 메서드는 배열에 저장된 n 번째 항목의 인덱스를 호출하는 함수를 만듭니다.
function nthIndexOf(search, n) {
var myArray = [];
for(var i = 0; i < myString.length; i++) { //loop thru string to check for occurrences
if(myStr.slice(i, i + search.length) === search) { //if match found...
myArray.push(i); //store index of each occurrence
}
}
return myArray[n - 1]; //first occurrence stored in index 0
}
사용 indexOf및 재귀 :
먼저 전달 된 n 번째 위치가 총 부분 문자열 발생 수보다 큰지 확인합니다. 전달되면 n 번째 인덱스를 찾을 때까지 각 인덱스를 재귀 적으로 살펴 봅니다.
var getNthPosition = function(str, sub, n) {
if (n > str.split(sub).length - 1) return -1;
var recursePosition = function(n) {
if (n === 0) return str.indexOf(sub);
return str.indexOf(sub, recursePosition(n - 1) + 1);
};
return recursePosition(n);
};
사용 [String.indexOf][1]
var stringToMatch = "XYZ 123 ABC 456 ABC 789 ABC";
function yetAnotherGetNthOccurance(string, seek, occurance) {
var index = 0, i = 1;
while (index !== -1) {
index = string.indexOf(seek, index + 1);
if (occurance === i) {
break;
}
i++;
}
if (index !== -1) {
console.log('Occurance found in ' + index + ' position');
}
else if (index === -1 && i !== occurance) {
console.log('Occurance not found in ' + occurance + ' position');
}
else {
console.log('Occurance not found');
}
}
yetAnotherGetNthOccurance(stringToMatch, 'ABC', 2);
// Output: Occurance found in 16 position
yetAnotherGetNthOccurance(stringToMatch, 'ABC', 20);
// Output: Occurance not found in 20 position
yetAnotherGetNthOccurance(stringToMatch, 'ZAB', 1)
// Output: Occurance not found
function getStringReminder(str, substr, occ) {
let index = str.indexOf(substr);
let preindex = '';
let i = 1;
while (index !== -1) {
preIndex = index;
if (occ == i) {
break;
}
index = str.indexOf(substr, index + 1)
i++;
}
return preIndex;
}
console.log(getStringReminder('bcdefgbcdbcd', 'bcd', 3));
StackOverflow에 대한 또 다른 질문에 대해 다음 코드를 가지고 놀았고 여기에 적절할 것이라고 생각했습니다. printList2 함수는 정규식의 사용을 허용하고 모든 발생을 순서대로 나열합니다. (printList는 이전 솔루션의 시도 였지만 여러 경우에 실패했습니다.)
<html>
<head>
<title>Checking regex</title>
<script>
var string1 = "123xxx5yyy1234ABCxxxabc";
var search1 = /\d+/;
var search2 = /\d/;
var search3 = /abc/;
function printList(search) {
document.writeln("<p>Searching using regex: " + search + " (printList)</p>");
var list = string1.match(search);
if (list == null) {
document.writeln("<p>No matches</p>");
return;
}
// document.writeln("<p>" + list.toString() + "</p>");
// document.writeln("<p>" + typeof(list1) + "</p>");
// document.writeln("<p>" + Array.isArray(list1) + "</p>");
// document.writeln("<p>" + list1 + "</p>");
var count = list.length;
document.writeln("<ul>");
for (i = 0; i < count; i++) {
document.writeln("<li>" + " " + list[i] + " length=" + list[i].length +
" first position=" + string1.indexOf(list[i]) + "</li>");
}
document.writeln("</ul>");
}
function printList2(search) {
document.writeln("<p>Searching using regex: " + search + " (printList2)</p>");
var index = 0;
var partial = string1;
document.writeln("<ol>");
for (j = 0; j < 100; j++) {
var found = partial.match(search);
if (found == null) {
// document.writeln("<p>not found</p>");
break;
}
var size = found[0].length;
var loc = partial.search(search);
var actloc = loc + index;
document.writeln("<li>" + found[0] + " length=" + size + " first position=" + actloc);
// document.writeln(" " + partial + " " + loc);
partial = partial.substring(loc + size);
index = index + loc + size;
document.writeln("</li>");
}
document.writeln("</ol>");
}
</script>
</head>
<body>
<p>Original string is <script>document.writeln(string1);</script></p>
<script>
printList(/\d+/g);
printList2(/\d+/);
printList(/\d/g);
printList2(/\d/);
printList(/abc/g);
printList2(/abc/);
printList(/ABC/gi);
printList2(/ABC/i);
</script>
</body>
</html>