자바스크립트에서 다른 문자열에 있는 모든 문자열의 인덱스를 찾는 방법은 무엇입니까?
다른 문자열에서 대소문자를 구분하지 않는 모든 문자열의 위치를 찾으려고 합니다.
예를 들어, 다음 문자열이 지정됩니다.
레바논에서 우쿨렐레를 배웠습니다.
문자열 " " 고검색문자열그리열"를 입력합니다.le
배열을 가져오려고 합니다.
[2, 25, 27, 33]
두 문자열 모두 변수가 됩니다. 즉, 값을 하드 코딩할 수 없습니다.
저는 이것이 정규 표현을 위한 쉬운 작업이라고 생각했지만, 효과적인 표현을 찾기 위해 한동안 고군분투했지만, 운이 없었습니다.
저는 이를 수행하는 방법의 예를 다음을 사용하여 찾았습니다..indexOf()
하지만 확실히 그것을 하는 더 간결한 방법이 있어야만 합니까?
var str = "I learned to play the Ukulele in Lebanon."
var regex = /le/gi, result, indices = [];
while ( (result = regex.exec(str)) ) {
indices.push(result.index);
}
갱신하다
원래 질문에서 검색 문자열이 변수여야 한다는 것을 발견하지 못했습니다.는 이 는저이사다위해다른버썼다습전니을루기건을▁to를 사용하는 다른 버전을 썼습니다indexOf
그래서 당신은 당신이 시작했던 곳으로 돌아갔습니다.Wrikken이 댓글에서 지적한 것처럼 정규 표현이 있는 일반적인 경우에 이를 수행하려면 특수 정규식 문자에서 벗어나야 할 것입니다. 이 시점에서 정규식 솔루션은 가치보다 골칫거리가 된다고 생각합니다.
function getIndicesOf(searchStr, str, caseSensitive) {
var searchStrLen = searchStr.length;
if (searchStrLen == 0) {
return [];
}
var startIndex = 0, index, indices = [];
if (!caseSensitive) {
str = str.toLowerCase();
searchStr = searchStr.toLowerCase();
}
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
indices.push(index);
startIndex = index + searchStrLen;
}
return indices;
}
var indices = getIndicesOf("le", "I learned to play the Ukulele in Lebanon.");
document.getElementById("output").innerHTML = indices + "";
<div id="output"></div>
(ES2020)을 사용하는 하나의 라이너:
[...sourceStr.matchAll(new RegExp(searchStr, 'gi'))].map(a => a.index)
값 사용:
const sourceStr = 'I learned to play the Ukulele in Lebanon.';
const searchStr = 'le';
const indexes = [...sourceStr.matchAll(new RegExp(searchStr, 'gi'))].map(a => a.index);
console.log(indexes); // [2, 25, 27, 33]
와 a 스프레드를 이약당신것하는걱그면다리고정된프를스.map()
한 줄로, 저는 그것을 운영했습니다.for...of
100만 번 반복합니다(스트링 사용).라이너 하나는 평균 1420ms인 반면,for...of
내 기계에서 평균 1150ms.그 정도면 큰 차이는 없지만, 몇 번의 경기만 한다면 라이너 하나가 잘 작동할 것입니다.
정규식 무료 버전은 다음과 같습니다.
function indexes(source, find) {
if (!source) {
return [];
}
// if find is empty string return all indexes.
if (!find) {
// or shorter arrow function:
// return source.split('').map((_,i) => i);
return source.split('').map(function(_, i) { return i; });
}
var result = [];
for (i = 0; i < source.length; ++i) {
// If you want to search case insensitive use
// if (source.substring(i, i + find.length).toLowerCase() == find) {
if (source.substring(i, i + find.length) == find) {
result.push(i);
}
}
return result;
}
indexes("I learned to play the Ukulele in Lebanon.", "le")
편집: 'aaaa' 및 'aa'와 같은 문자열을 일치시켜 [0, 2]를 찾으려면 다음 버전을 사용합니다.
function indexes(source, find) {
if (!source) {
return [];
}
if (!find) {
return source.split('').map(function(_, i) { return i; });
}
var result = [];
var i = 0;
while(i < source.length) {
if (source.substring(i, i + find.length) == find) {
result.push(i);
i += find.length;
} else {
i++;
}
}
return result;
}
당신은 정말 할 수 있어요!
//make a regular expression out of your needle
var needle = 'le'
var re = new RegExp(needle,'gi');
var haystack = 'I learned to play the Ukulele';
var results = new Array();//this is the results you want
while (re.exec(haystack)){
results.push(re.lastIndex);
}
편집: RegExp의 철자를 배웁니다.
그리고 이게 정확히 당신이 원하는 게 아니라는 걸 깨달았어요lastIndex
바늘의 끝이 시작이 아니라 가깝다는 것을 알려줍니다. 밀 수 있습니다.re.lastIndex-needle.length
결과 배열로...
편집: 링크 추가
@Tim Down의 응답은 RegExp.exec()의 결과 개체를 사용하며, 내 모든 Javascript 리소스는 일치하는 문자열을 제공하는 것을 제외하고 사용을 얼버무립니다.그래서 그가 사용할 때result.index
일종의 이름 없는 매치 오브제입니다.exec에 대한 MDC 설명에서는 실제로 이 개체를 상당히 자세히 설명합니다.
파티에 조금 늦었지만(거의 10년, 2개월 정도) 미래의 코더들을 위한 한 가지 방법은 루프와indexOf()
let haystack = "I learned to play the Ukulele in Lebanon.";
let needle = "le";
let pos = 0; // Position Ref
let result = []; // Final output of all index's.
let hayStackLower = haystack.toLowerCase();
// Loop to check all occurrences
while (hayStackLower.indexOf(needle, pos) != -1) {
result.push(hayStackLower.indexOf(needle , pos));
pos = hayStackLower.indexOf(needle , pos) + 1;
}
console.log("Final ", result); // Returns all indexes or empty array if not found
만약 당신이 모든 매치의 위치를 찾고 싶다면, 나는 당신에게 약간의 해킹을 지적하고 싶습니다.
var haystack = 'I learned to play the Ukulele in Lebanon.',
needle = 'le',
splitOnFound = haystack.split(needle).map(function (culm)
{
return this.pos += culm.length + needle.length
}, {pos: -needle.length}).slice(0, -1); // {pos: ...} – Object wich is used as this
console.log(splitOnFound);
길이가 가변적인 RegExp가 있는 경우에는 적용할 수 없지만 일부의 경우에는 유용할 수 있습니다.
대소문자를 구분합니다.하지 않는 에는 케스불증용을 합니다.String.toLowerCase
전에 기능합니다.
const findAllOccurrences = (str, substr) => {
str = str.toLowerCase();
let result = [];
let idx = str.indexOf(substr)
while (idx !== -1) {
result.push(idx);
idx = str.indexOf(substr, idx+1);
}
return result;
}
console.log(findAllOccurrences('I learned to play the Ukulele in Lebanon', 'le'));
팀의 답변을 추천합니다.그러나 @blazz의 이 논평은 다음과 같습니다.searchStr=aaa
그 그에밖str=aaaaaa
대신 수 . Tim의 이 입니다. "Str.length"는 다음과 같습니다. "Str.length"는 4번째 줄입니다. "Tim"입니다.startIndex = index + searchStrLen;
Tim의 코드는 자신의 길이 내에서 검색 중인 문자열의 인스턴스를 찾을 수 없습니다.저는 팀의 그서팀답변수을정다니습했의래다니▁tim▁so.
function getIndicesOf(searchStr, str, caseSensitive) {
var startIndex = 0, index, indices = [];
if (!caseSensitive) {
str = str.toLowerCase();
searchStr = searchStr.toLowerCase();
}
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
indices.push(index);
startIndex = index + 1;
}
return indices;
}
var searchStr = prompt("Enter a string.");
var str = prompt("What do you want to search for in the string?");
var indices = getIndicesOf(str, searchStr);
document.getElementById("output").innerHTML = indices + "";
<div id="output"></div>
으로 변경+ 1
에 + searchStrLen
" " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " "aaaaaa
그리검스드의 .aaa
.
추신. 코드에 코드가 어떻게 작동하는지 설명하는 코멘트를 원하는 사람이 있다면 그렇게 말씀해 주십시오. 요청에 기꺼이 응답하겠습니다.
다음은 간단한 코드 조각입니다.
function getIndexOfSubStr(str, searchToken, preIndex, output) {
var result = str.match(searchToken);
if (result) {
output.push(result.index +preIndex);
str=str.substring(result.index+searchToken.length);
getIndexOfSubStr(str, searchToken, preIndex, output)
}
return output;
}
var str = "my name is 'xyz' and my school name is 'xyz' and my area name is 'xyz' ";
var searchToken ="my";
var preIndex = 0;
console.log(getIndexOfSubStr(str, searchToken, preIndex, []));
모든 답변에 감사드립니다.저는 그것들을 모두 조사해서 '니들' 하위 문자열의 각 발생에 대한 마지막 인덱스를 첫 번째로 제공하는 기능을 생각해 냈습니다. 누군가에게 도움이 될 것을 대비하여 여기에 게시합니다.
각 발생의 시작에 대한 원래 요청과 동일하지 않습니다.바늘 길이를 유지할 필요가 없기 때문에 제 유스케이스에 더 잘 맞습니다.
function findRegexIndices(text, needle, caseSensitive){
var needleLen = needle.length,
reg = new RegExp(needle, caseSensitive ? 'gi' : 'g'),
indices = [],
result;
while ( (result = reg.exec(text)) ) {
indices.push([result.index, result.index + needleLen]);
}
return indices
}
동일한 문자열도 찾을 수 있는 이 솔루션을 확인하십시오. 누락된 부분이 있는지 없는지 알려주십시오.
function indexes(source, find) {
if (!source) {
return [];
}
if (!find) {
return source.split('').map(function(_, i) { return i; });
}
source = source.toLowerCase();
find = find.toLowerCase();
var result = [];
var i = 0;
while(i < source.length) {
if (source.substring(i, i + find.length) == find)
result.push(i++);
else
i++
}
return result;
}
console.log(indexes('aaaaaaaa', 'aaaaaa'))
console.log(indexes('aeeaaaaadjfhfnaaaaadjddjaa', 'aaaa'))
console.log(indexes('wordgoodwordgoodgoodbestword', 'wordgood'))
console.log(indexes('I learned to play the Ukulele in Lebanon.', 'le'))
@jcubic의 대답을 따르세요, 그의 해결책은 제 경우에 작은 혼란을 일으켰습니다.
를 들어 를들면입니다.var result = indexes('aaaa', 'aa')
돌아올 것입니다[0, 1, 2]
에 [0, 2]
그래서 나는 그의 해결책을 아래와 같이 나의 경우에 맞게 업데이트했습니다.
function indexes(text, subText, caseSensitive) {
var _source = text;
var _find = subText;
if (caseSensitive != true) {
_source = _source.toLowerCase();
_find = _find.toLowerCase();
}
var result = [];
for (var i = 0; i < _source.length;) {
if (_source.substring(i, i + _find.length) == _find) {
result.push(i);
i += _find.length; // found a subText, skip to next position
} else {
i += 1;
}
}
return result;
}
다음은 내 코드입니다(검색 및 조각 방법 사용).
let s = "I learned to play the Ukulele in Lebanon"
let sub = 0
let matchingIndex = []
let index = s.search(/le/i)
while( index >= 0 ){
matchingIndex.push(index+sub);
sub = sub + ( s.length - s.slice( index+1 ).length )
s = s.slice( index+1 )
index = s.search(/le/i)
}
console.log(matchingIndex)
이것은 위치에 따라 문자열 인덱스를 얻을 때 주로 사용하는 것입니다.
다음 매개 변수를 전달합니다.
검색: 검색할 문자열
찾기: 찾을 문자열
position('all' 기본값): 검색 문자열에서 찾기 문자열이 나타나는 위치
('all'인 경우 인덱스의 전체 배열을 반환합니다.)
('마지막'인 경우 마지막 위치를 반환합니다.)
function stringIndex (search, find, position = "all") {
var currIndex = 0, indexes = [], found = true;
while (found) {
var searchIndex = search.indexOf(find);
if (searchIndex > -1) {
currIndex += searchIndex + find.length;
search = search.substr (searchIndex + find.length);
indexes.push (currIndex - find.length);
} else found = false; //no other string to search for - exit from while loop
}
if (position == 'all') return indexes;
if (position > indexes.length -1) return [];
position = (position == "last") ? indexes.length -1 : position;
return indexes[position];
}
//Example:
var myString = "Joe meets Joe and together they go to Joe's house";
console.log ( stringIndex(myString, "Joe") ); //0, 10, 38
console.log ( stringIndex(myString, "Joe", 1) ); //10
console.log ( stringIndex(myString, "Joe", "last") ); //38
console.log ( stringIndex(myString, "Joe", 5) ); //[]
안녕 친구들 이것은 축소와 도우미 방법을 사용하여 일치하는 구문의 인덱스를 찾는 또 다른 방법일 뿐입니다.물론 RegExp가 더 편리하고 내부적으로 이렇게 구현될 수도 있습니다.도움이 되길 바랍니다.
function findIndexesOfPhraseWithReduce(text, phrase) { //convert text to array so that be able to manipulate. const arrayOfText = [...text]; /* this function takes the array of characters and the search phrase and start index which comes from reduce method and calculates the end with length of the given phrase then slices and joins characters and compare it whith phrase. and returns True Or False */ function isMatch(array, phrase, start) { const end = start + phrase.length; return (array.slice(start, end).join('')).toLowerCase() === phrase.toLowerCase(); } /* here we reduce the array of characters and test each character with isMach function which takes "current index" and matches the phrase with the subsequent character which starts from current index and ends at the last character of phrase(the length of phrase). */ return arrayOfText.reduce((acc, item, index) => isMatch(arrayOfText, phrase, index) ? [...acc, index] : acc, []); } findIndexesOfPhraseWithReduce("I learned to play the Ukulele in Lebanon.", "le");
function findIndexesOfPhraseWithReduce(text, phrase) {
const arrayOfText = [...text];
function isMatch(array, phrase, start) {
const end = start + phrase.length;
return (array.slice(start, end).join('')).toLowerCase() ===
phrase.toLowerCase();
}
return arrayOfText.reduce((acc, item, index) => isMatch(arrayOfText, phrase,
index) ? [...acc, index] : acc, []);
}
console.log(findIndexesOfPhraseWithReduce("I learned to play the Ukulele in Lebanon.", "le"));
function countInString(searchFor,searchIn){
var results=0;
var a=searchIn.indexOf(searchFor)
while(a!=-1){
searchIn=searchIn.slice(a*1+searchFor.length);
results++;
a=searchIn.indexOf(searchFor);
}
return results;
}
아래 코드가 당신에게 도움이 될 것입니다:
function indexes(source, find) {
var result = [];
for(i=0;i<str.length; ++i) {
// If you want to search case insensitive use
// if (source.substring(i, i + find.length).toLowerCase() == find) {
if (source.substring(i, i + find.length) == find) {
result.push(i);
}
}
return result;
}
indexes("hello, how are you", "ar")
String.prototype.match를 사용합니다.
다음은 MDN 문서 자체의 예입니다.
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var regexp = /[A-E]/gi;
var matches_array = str.match(regexp);
console.log(matches_array);
// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']
언급URL : https://stackoverflow.com/questions/3410464/how-to-find-indices-of-all-occurrences-of-one-string-in-another-in-javascript
'itsource' 카테고리의 다른 글
하나의 명령으로 PowerShell의 여러 전경색 표시 (0) | 2023.08.10 |
---|---|
여러 클래스를 기준으로 요소 선택 (0) | 2023.08.10 |
iPhone HTML5 비디오 재생 버튼 숨기기 (0) | 2023.08.10 |
inject()는 주입 컨텍스트에서 호출되어야 합니다. (0) | 2023.08.10 |
도커 리포지토리 이름을 변경하거나 이미지 이름을 변경하는 방법은 무엇입니까? (0) | 2023.08.10 |