programing

문자열에 JavaScript의 하위 문자열 배열 텍스트가 포함되어 있는지 확인하는 방법

bestcode 2022. 9. 30. 11:13
반응형

문자열에 JavaScript의 하위 문자열 배열 텍스트가 포함되어 있는지 확인하는 방법

꽤 직설적이죠javascript에서는 문자열에 배열에 포함된 서브스트링이 있는지 확인해야 합니다.

을 할 수 있는 ''으로할 수 .기능을 작성해야 합니다.단, 이 기능은 콜백에 불과할 수도 있습니다.some배열 방식

두 가지 접근 방식:

  • ★★★★some
  • 정규 표현

★★★★some

" " "somemethod는.method (ES5 in를) 、 method ( ES5 를 ) 。

if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) {
    // There's at least one
}

화살표 기능과 새로운 기능을 통해 더욱 우수합니다.includesES2015+:

if (substrings.some(v => str.includes(v))) {
    // There's at least one
}

라이브 예:

const substrings = ["one", "two", "three"];
let str;

// Setup
console.log(`Substrings: ${substrings}`);

// Try it where we expect a match
str = "this has one";
if (substrings.some(v => str.includes(v))) {
    console.log(`Match using "${str}"`);
} else {
    console.log(`No match using "${str}"`);
}

// Try it where we DON'T expect a match
str = "this doesn't have any";
if (substrings.some(v => str.includes(v))) {
    console.log(`Match using "${str}"`);
} else {
    console.log(`No match using "${str}"`);
}

정규 표현

문자열에 정규 표현에서 특별한 문자가 포함되어 있지 않은 경우 다음과 같이 속일 수 있습니다.

if (new RegExp(substrings.join("|")).test(string)) {
    // At least one match
}

...필요한 서브스트링에 대한 일련의 교대로 정규 표현을 만듭니다(예:one|two중 하는 것이 만, 어느 되어 있지 여부를 테스트합니다(「 」 「 」 「 」 「 」 「 」 「 」 「 」 「 」 「 」 「 」*,[먼저 탈출해야 하고 대신 지루한 루프를 하는 것이 좋습니다.이스케이프에 대한 자세한 내용은 이 질문의 답변을 참조하십시오.

라이브 예:

const substrings = ["one", "two", "three"];
let str;

// Setup
console.log(`Substrings: ${substrings}`);

// Try it where we expect a match
str = "this has one";
if (new RegExp(substrings.join("|")).test(str)) {
    console.log(`Match using "${str}"`);
} else {
    console.log(`No match using "${str}"`);
}

// Try it where we DON'T expect a match
str = "this doesn't have any";
if (new RegExp(substrings.join("|")).test(str)) {
    console.log(`Match using "${str}"`);
} else {
    console.log(`No match using "${str}"`);
}

단일 라인 솔루션

substringsArray.some(substring=>yourBigString.includes(substring))

true\false 「」의 경우exists\does'nt exist

ES6 지원 필요

var yourstring = 'tasty food'; // the string to check against


var substrings = ['foo','bar'],
    length = substrings.length;
while(length--) {
   if (yourstring.indexOf(substrings[length])!=-1) {
       // one of the substrings is in yourstring
   }
}
function containsAny(str, substrings) {
    for (var i = 0; i != substrings.length; i++) {
       var substring = substrings[i];
       if (str.indexOf(substring) != - 1) {
         return substring;
       }
    }
    return null; 
}

var result = containsAny("defg", ["ab", "cd", "ef"]);
console.log("String was found in substring " + result);

구글 검색하시는 분들은

확실한 답은 다음과 같습니다.

const substrings = ['connect', 'ready'];
const str = 'disconnect';
if (substrings.some(v => str === v)) {
   // Will only return when the `str` is included in the `substrings`
}

지금까지 최고의 솔루션(IMO)을 소개합니다.다음과 같은 최신(ES6) 솔루션입니다.

  • 효율적입니다(1줄!)
  • 루프를 회피
  • 는 the와는 some()부울false)만.
  • 대신 하위 문자열(배열에서 발견된 경우)을 반환하거나 정의되지 않은 값을 반환합니다.
  • 한 걸음 더 나아가 부분적인 서브스트링 일치가 필요한지 여부를 선택할 수 있습니다(아래 참조).

맛있게 드세요!



const arrayOfStrings = ['abc', 'def', 'xyz'];
const str = 'abc';
const found = arrayOfStrings.find(v => (str === v));

서서,,found이 경우 'display'로 설정됩니다.이것은 문자열이 정확히 일치할 때 작동합니다.

대신 다음을 사용하는 경우:

const found = arrayOfStrings.find(v => str.includes(v));

한 번 말씀드리지만,found표시하다일치를 이 '로 되어 있는 str 'ab'는 'ab'로 설정되어 있습니다.found정의되지 않습니다.


And, if you want partial matches to work, simply flip it so you're doing:
const found = arrayOfStrings.find(v => v.includes(str));

'ab로 설정되어 경우 str'ab'은 'ab'로 설정되어 있습니다.found로 됩니다.

쉬워요!



var str = "texttexttext";
var arr = ["asd", "ghj", "xtte"];
for (var i = 0, len = arr.length; i < len; ++i) {
    if (str.indexOf(arr[i]) != -1) {
        // str contains arr[i]
    }
}

edit: 테스트 순서가 중요하지 않은 경우 다음과 같이 사용할 수 있습니다(루프 변수는 1개뿐).

var str = "texttexttext";
var arr = ["asd", "ghj", "xtte"];
for (var i = arr.length - 1; i >= 0; --i) {
    if (str.indexOf(arr[i]) != -1) {
        // str contains arr[i]
    }
}
substringsArray.every(substring=>yourBigString.indexOf(substring) === -1)

완전한 지원을 위해;)

풀 서포트(@ricca 버전 추가)

wordsArray = ['hello', 'to', 'nice', 'day']
yourString = 'Hello. Today is a nice day'.toLowerCase()
result = wordsArray.every(w => yourString.includes(w))
console.log('result:', result)

어레이가 크지 않은 경우 다음 명령어를 사용하여 각 서브스트링에 대해 스트링을 개별적으로 루프하고 체크할 수 있습니다.indexOf()또는 기판을 대체한 정규식을 작성할 수 있습니다.이것이 더 효율적일 수도 있고 그렇지 않을 수도 있습니다.

Javascript 기능은 검색 문자열 또는 검색 문자열 배열을 사용하여 태그 또는 키워드 배열을 검색합니다.(ES5 일부 어레이 방식 및 ES6 화살표 기능 사용)

// returns true for 1 or more matches, where 'a' is an array and 'b' is a search string or an array of multiple search strings
function contains(a, b) {
    // array matches
    if (Array.isArray(b)) {
        return b.some(x => a.indexOf(x) > -1);
    }
    // string match
    return a.indexOf(b) > -1;
}

사용 예:

var a = ["a","b","c","d","e"];
var b = ["a","b"];
if ( contains(a, b) ) {
    // 1 or more matches found
}

너무 늦었지만 방금 이 문제에 부딪혔어요.제 프로젝트에서는 다음 항목을 사용하여 문자열이 배열에 있는지 확인했습니다.

["a","b"].includes('a')     // true
["a","b"].includes('b')     // true
["a","b"].includes('c')     // false

이렇게 하면 미리 정의된 배열에 문자열이 포함되어 있는지 확인할 수 있습니다.

var parameters = ['a','b']
parameters.includes('a')    // true

최적의 답은 다음과 같습니다.이것도 대소문자를 구분하지 않는다.

    var specsFilter = [.....];
    var yourString = "......";

    //if found a match
    if (specsFilter.some((element) => { return new RegExp(element, "ig").test(yourString) })) {
        // do something
    }

확장/수정할 것을 제안하는 것은 아닙니다.String의 프로토타입이지만, 이게 제가 한 일입니다.

String.protype.includes()

String.prototype.includes = function (includes) {
    console.warn("String.prototype.includes() has been modified.");
    return function (searchString, position) {
        if (searchString instanceof Array) {
            for (var i = 0; i < searchString.length; i++) {
                if (includes.call(this, searchString[i], position)) {
                    return true;
                }
            }
            return false;
        } else {
            return includes.call(this, searchString, position);
        }
    }
}(String.prototype.includes);

console.log('"Hello, World!".includes("foo");',          "Hello, World!".includes("foo")           ); // false
console.log('"Hello, World!".includes(",");',            "Hello, World!".includes(",")             ); // true
console.log('"Hello, World!".includes(["foo", ","])',    "Hello, World!".includes(["foo", ","])    ); // true
console.log('"Hello, World!".includes(["foo", ","], 6)', "Hello, World!".includes(["foo", ","], 6) ); // false

T에 건물을 짓습니다.J Crowder의 대답

이스케이프된 RegExp를 사용하여 적어도1개의 서브스트링의 "최소 1회" 발생을 테스트합니다.

function buildSearch(substrings) {
  return new RegExp(
    substrings
    .map(function (s) {return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');})
    .join('{1,}|') + '{1,}'
  );
}


var pattern = buildSearch(['hello','world']);

console.log(pattern.test('hello there'));
console.log(pattern.test('what a wonderful world'));
console.log(pattern.test('my name is ...'));

T.J. Crowder의 솔루션에서 이 문제를 해결하기 위해 프로토타입을 만들었습니다.

Array.prototype.check = function (s) {
  return this.some((v) => {
    return s.indexOf(v) >= 0;
  });
};

언더스코어.js 또는 lodash.js를 사용하면 문자열 배열에서 다음 작업을 수행할 수 있습니다.

var contacts = ['Billy Bob', 'John', 'Bill', 'Sarah'];

var filters = ['Bill', 'Sarah'];

contacts = _.filter(contacts, function(contact) {
    return _.every(filters, function(filter) { return (contact.indexOf(filter) === -1); });
});

// ['John']

그리고 하나의 문자열로:

var contact = 'Billy';
var filters = ['Bill', 'Sarah'];

_.every(filters, function(filter) { return (contact.indexOf(filter) >= 0); });

// true

공백이나 다른 공통 문자로 구분된 완전한 "단어"로 구성된 긴 하위 문자열 목록을 사용하는 경우 검색에 조금 더 현명할 수 있습니다.

먼저 문자열을 X 그룹으로 나눈 다음 X+1, X+2, ..., Y까지의 하위 문자열에 있는 단어 수가 각각 가장 적은 단어와 가장 많은 단어 수여야 합니다.예를 들어 X가 1이고 Y가 4인 경우 "Alpha Beta Gamma Delta"는 다음과 같습니다.

'알파' '베타' '감마' '델타'

'알파 베타' '베타 감마' '감마 델타'

"알파 베타 감마" "베타 감마 델타"

알파 베타 감마 델타

X가 2이고 Y가 3이면 첫 번째 행과 마지막 행을 생략합니다.

이제 이 목록을 세트(또는 맵)에 삽입하면 문자열 비교보다 훨씬 빠르게 이 목록을 검색할 수 있습니다.

단점은 "ta Gamm"과 같은 서브스트링을 검색할 수 없다는 것입니다.물론, 단어별이 아닌 문자별로 분할하는 것으로 이를 허용할 수 있지만, 그렇게 하려면 많은 경우 대량의 세트를 구축해야 하고, 그렇게 하는 데 소요되는 시간과 메모리는 이점보다 더 중요합니다.

convert_to_array = function (sentence) {
     return sentence.trim().split(" ");
};

let ages = convert_to_array ("I'm a programmer in javascript writing script");

function confirmEnding(string) {
let target = "ipt";
    return  (string.substr(-target.length) === target) ? true : false;
}

function mySearchResult() {
return ages.filter(confirmEnding);
}

mySearchResult();

이렇게 확인하고 필터를 사용하여 일치하는 단어 배열을 반환할 수 있습니다.

나는 이런 문제가 있었다.URL이 있어서 링크가 이미지 포맷으로 끝나는지 다른 파일 포맷으로 끝나는지 확인하고 싶었습니다.제가 한 일은 다음과 같습니다.

const imagesFormat = ['.jpg','.png','.svg']
const link = "https://res.cloudinary.com/***/content/file_padnar.pdf"
const isIncludes = imagesFormat.some(format => link.includes(format))
    
// false

다음과 같이 확인할 수 있습니다.

<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
      <script>
         $(document).ready(function(){
         var list = ["bad", "words", "include"] 
         var sentence = $("#comments_text").val()

         $.each(list, function( index, value ) {
           if (sentence.indexOf(value) > -1) {
                console.log(value)
            }
         });
         });
      </script>
   </head>
   <body>
      <input id="comments_text" value="This is a bad, with include test"> 
   </body>
</html>

const str = 'Does this string have one or more strings from the array below?';
const arr = ['one', 'two', 'three'];

const contains = arr.some(element => {
  if (str.includes(element)) {
    return true;
  }
  return false;
});

console.log(contains); // true

let obj = [{name : 'amit'},{name : 'arti'},{name : 'sumit'}];
let input = 'it';

필터 사용:

obj.filter((n)=> n.name.trim().toLowerCase().includes(input.trim().toLowerCase()))

var str = "A for apple"
var subString = ["apple"]

console.log(str.includes(subString))

언급URL : https://stackoverflow.com/questions/5582574/how-to-check-if-a-string-contains-text-from-an-array-of-substrings-in-javascript

반응형