简体   繁体   中英

How to check whether a string contains a substring in JavaScript(typescript)?

I'm trying to make a search field, and I'm already able to do searches, but it only returns posts that are typed with the same title or are exactly the same which would not be interesting. This happens in my conditional if (query.== post.title && query) return null . The ideal would be to search just one word and return similar posts. I've tried using the includes method as follows:

if (query.== post.title && query.includes(post.title) && query) return null

but it didn't work.

I tried post.title.includes(query) too, but when I add this condition the post that I type on input is removed and it returns all the others, and if I remove the query.== post.title the search doesn't will work because query in my logic is the value that comes from the input.

{(() => {
  if (isLoading) return <LoadingBlock />
  if (!isLoading && postList.length === 0) return <NoDataWarning text='Nenhuma postagem encontrada.' />
  return postList.map((post, index) => {
    if (query !== post.title && query.includes(post.title) && query) return null //the problem is here
    return (
      <PostContainer position={index}>
        <PostBanner />
        <PostInfoContainer>
          <span>
            <AiFillCalendar />
            {new Date(post.createdAt).toLocaleDateString()}
          </span>
          <span>
            <FaUserCircle />
            {`${post.firstName} ${post.lastName}`}
          </span>
        </PostInfoContainer>
        <PostTitle>{post.title}</PostTitle>
      </PostContainer>
    )

Full code

import React, { useState, useEffect, useCallback } from 'react'
import api from 'services/api'
import { Link } from 'react-router-dom'
import { RectShape } from 'react-placeholder/lib/placeholders'
import { AiFillCalendar } from 'react-icons/ai'
import { FaUserCircle } from 'react-icons/fa'
import NoDataWarning from 'components/NoDataWarning'
import Can from 'components/Can'
import PayPlaceholder from 'components/PayPlaceholder'
import { Post } from 'types'

import { ButtonIcon, SearchGroup, SearchInput } from 'components/SearchBar/styles'
import { BiSearchAlt2 } from 'react-icons/bi'
import { Container, PostContainer, PostTitle, PostBanner, PostInfoContainer, PostGrid } from './styles'

const RegulatorioList: React.FC = () => {
  const [postList, setPostList] = useState<Post[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [query, setQuery] = useState('')
  const [result, setResult] = useState<Post[] | undefined>()

  const inputHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
    const enteredName = event.target.value
    setQuery(enteredName)
  }

  // This function is triggered when the Search buttion is clicked
  const search = () => {
    const foundItems = postList.filter(postList => postList.title.toLowerCase().includes(query.toLowerCase()))
    setResult(foundItems)
  }

  const fetchPosts = useCallback(() => {
    api
      .get<Post[]>('posts', { params: { filterInactives: true } })
      .then(response => {
        setPostList(response.data)
        setIsLoading(false)
      })
  }, [])

  useEffect(() => {
    fetchPosts()
    const interval = setInterval(fetchPosts, 180000)
    return () => clearInterval(interval)
  }, [fetchPosts])

  const LoadingBlock = () => (
    <>
      {new Array(15).fill('').map(() => (
        <RectShape color='lightgray' style={{ width: '100%', height: '350px', borderRadius: '5px' }} className='text-block' />
      ))}
    </>
  )

  return (
    <Container>
      <SearchGroup position={1}>
        <SearchInput value={query} onChange={inputHandler} placeholder='Search ' />
        <ButtonIcon type='button' onClick={search}>
          <BiSearchAlt2 />
        </ButtonIcon>
      </SearchGroup>
      <PostGrid>
        {(() => {
          if (isLoading) return <LoadingBlock />
          if (!isLoading && postList.length === 0) return <NoDataWarning text='Nenhuma postagem encontrada.' />
          return postList.map((post, index) => {
            // if (post.title.includes(query) !== post.title && query) return null
            // if (query !== indexOf(post.title) && query) return null
            // if (query !== post.title && post.title.includes(post.title) && query) return null //ALL TRYS
            // if (query !== post.title && query) return null
            if (query !== post.title && query) return null
            return null
            return (
              <PostContainer position={index}>
                <PostBanner />
                <PostInfoContainer>
                  <span>
                    <AiFillCalendar />
                    {new Date(post.createdAt).toLocaleDateString()}
                  </span>
                  <span>
                    <FaUserCircle />
                    {`${post.firstName} ${post.lastName}`}
                  </span>
                </PostInfoContainer>
                <PostTitle>{post.title}</PostTitle>
              </PostContainer>
            )
            return (
              <Link key={post.id} to={`/regulatorio/${post.id}`} style={{ textDecoration: 'none', height: '100%' }}>
                <PostContainer position={index}>
                  <PostBanner />
                  <PostInfoContainer>
                    <span>
                      <AiFillCalendar />
                      {new Date(post.createdAt).toLocaleDateString()}
                    </span>
                    <span>
                      <FaUserCircle />
                      {`${post.firstName} ${post.lastName}`}
                    </span>
                  </PostInfoContainer>
                  <PostTitle>{post.title}</PostTitle>
                </PostContainer>
              </Link>
            )
          })
        })()}
      </PostGrid>
    </Container>
  )
}

export default RegulatorioList

I solve this with this conditional

 if (!post.title.toLowerCase().includes(query.toLowerCase()) && query) return null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM