简体   繁体   English

React / Javascript - 从输入字段(搜索栏)中删除字符串两端的空格和单词之间的额外空格

[英]React / Javascript - Remove white spaces from both ends of a string and extra spaces between words, from a input field (search bar)

I have a search bar that fetches movies from an API with the name of the movie [ on every keystroke].我有一个搜索栏,可以从带有电影名称的 API 中获取电影 [每次击键时]。
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" " gran torino " ==> "gran torino"
" Pirates of the Caribbean " ==> "Pirates of the Caribbean" " 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.. - .trim() 不允许我在单词之间使用空格..
- onBlur won't help either because i wont unfocus from the search bar. - onBlur 也无济于事,因为我不会从搜索栏中失去焦点。 ( Remove white spaces from both ends of a string inside a form - React ) 从表单内的字符串两端删除空格 - React
- several regex expressions that i tried wouldn't allow spaces between words to (like .trim()) ( https://stackoverflow.com/a/7636022/3186426 ) - 我尝试过的几个正则表达式不允许单词之间有空格(如 .trim())( https://stackoverflow.com/a/7636022/3186426

How can i do it??我该怎么做?? Im i missing something?我错过了什么?
Thank you!谢谢!

 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.您可以让用户在输入中输入他们想要的任何内容,在执行该 API 调用之前,您可以使用上面的removeExtraSpace示例删除空格,然后当请求完成时,如果您想更新输入值,则可以。

Check the example: https://codesandbox.io/s/trim-before-8efz5检查示例: https : //codesandbox.io/s/trim-before-8efz5

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

With a simple and quick one liner.使用简单快捷的单衬。

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

// "Pirates of the Caribbean"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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