最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - ReactJavascript - Remove white spaces from both ends of a string and extra spaces between words, from a input field (s

programmeradmin4浏览0评论

I have a search bar that fetches movies from an API with the name of the movie [ on every keystroke].
I want to trim the extra spaces from both before and after the name, and only have one space between words..

[It should send the clean string to the query to be fetched]

example:
[(what i'm typing) ==> (what should be queried)]
" gran torino " ==> "gran torino"
" Pirates of the Caribbean " ==> "Pirates of the Caribbean"

search field
state value

code:

const fetchMovieList = async (query) => {
        if (query !== '') {
            setStatusFetch('loading');
            try {
                const res = await fetch(`[API]=${query}`);
                const movieListFromApi = await res.json();
                if (movieListFromApi.Response === 'True') {
                    setStatusFetch('resolved');
                    setStatusMovie('found');
                    setMovieList(movieListFromApi.Search);
                } else {
                    setMovieList([]);
                    setStatusMovie('notFound');
                }
                setStatusFetch('idle');
            } catch (error) {
                setStatusFetch('rejected');
            }
        } else {
            setMovieList([]);
            setStatusMovie('');
        }
    };
const myDebouncedFunction = useCallback(debounce((query) => fetchMovieList(query), 1000), []);
const handleSearch = ({ target: { value: inputValue } }) => {
    setSearchInputValue(inputValue);
    myDebouncedFunction(inputValue);
};
<SearchBar 
    type='text' 
    name='query' 
    placeholder='Search movies...' 
    value={searchInputValue} 
    onChange={handleSearch} 
    icon='fa fa-search' />

NON WORKING SOLUTIONS
- .trim() doesn't allow me to use spaces between words..
- onBlur won't help either because i wont unfocus from the search bar. (Remove white spaces from both ends of a string inside a form - React)
- several regex expressions that i tried wouldn't allow spaces between words to (like .trim()) ()

How can i do it?? Im i missing something?
Thank you!

I have a search bar that fetches movies from an API with the name of the movie [ on every keystroke].
I want to trim the extra spaces from both before and after the name, and only have one space between words..

[It should send the clean string to the query to be fetched]

example:
[(what i'm typing) ==> (what should be queried)]
" gran torino " ==> "gran torino"
" Pirates of the Caribbean " ==> "Pirates of the Caribbean"

search field
state value

code:

const fetchMovieList = async (query) => {
        if (query !== '') {
            setStatusFetch('loading');
            try {
                const res = await fetch(`[API]=${query}`);
                const movieListFromApi = await res.json();
                if (movieListFromApi.Response === 'True') {
                    setStatusFetch('resolved');
                    setStatusMovie('found');
                    setMovieList(movieListFromApi.Search);
                } else {
                    setMovieList([]);
                    setStatusMovie('notFound');
                }
                setStatusFetch('idle');
            } catch (error) {
                setStatusFetch('rejected');
            }
        } else {
            setMovieList([]);
            setStatusMovie('');
        }
    };
const myDebouncedFunction = useCallback(debounce((query) => fetchMovieList(query), 1000), []);
const handleSearch = ({ target: { value: inputValue } }) => {
    setSearchInputValue(inputValue);
    myDebouncedFunction(inputValue);
};
<SearchBar 
    type='text' 
    name='query' 
    placeholder='Search movies...' 
    value={searchInputValue} 
    onChange={handleSearch} 
    icon='fa fa-search' />

NON WORKING SOLUTIONS
- .trim() doesn't allow me to use spaces between words..
- onBlur won't help either because i wont unfocus from the search bar. (Remove white spaces from both ends of a string inside a form - React)
- several regex expressions that i tried wouldn't allow spaces between words to (like .trim()) (https://stackoverflow./a/7636022/3186426)

How can i do it?? Im i missing something?
Thank you!

Share Improve this question edited Mar 31, 2020 at 15:22 astroboy asked Mar 18, 2020 at 18:30 astroboyastroboy 531 gold badge1 silver badge5 bronze badges 1
  • Does this answer your question? remove extra spaces in string javascript – Emile Bergeron Commented Mar 18, 2020 at 18:53
Add a ment  | 

4 Answers 4

Reset to default 7

const test = "  Pirates  of      the    Caribbean     ";

const removeExtraSpace = (s) => s.trim().split(/ +/).join(' ');

console.log(removeExtraSpace(test))

You may want to check if string is empty first

It looks like you are trying to trim an input while you are typing. If you trim while you type, you will not be able to add spaces between text.

You can let the user type whatever they want on the input, and before you do that API call, you remove the spaces using the removeExtraSpace example above, and then when the request finish you can, if you want update the input value.

Check the example: https://codesandbox.io/s/trim-before-8efz5

With a simple and quick one liner.

"  Pirates  of      the    Caribbean     ".replace(/\s{2,}/g,' ').trim() 

// "Pirates of the Caribbean"

    let data="  Pirates  of      the    Caribbean     "
    let data1=data.trim().split('  ').filter(word=>word!=='')
    console.log(data1)
   data=data1.join(' ')
    console.log("Data=",data)

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论