【发布时间】:2020-06-29 21:35:29
【问题描述】:
我有一个搜索栏,可以从 API 中获取带有电影名称的电影 [每次击键时]。
我想修剪名字前后多余的空格,单词之间只有一个空格..
[它应该将干净的字符串发送到要获取的查询]
示例:
[(我输入的内容)==>(应该查询的内容)]" gran torino " ==> "gran torino"" Pirates of the Caribbean " ==> "Pirates of the Caribbean"
代码:
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' />
无效的解决方案
- .trim() 不允许我在单词之间使用空格..
- onBlur 也无济于事,因为我不会从搜索栏中失去焦点。 (Remove white spaces from both ends of a string inside a form - React)
- 我尝试过的几个正则表达式不允许单词之间有空格(如 .trim()) (https://stackoverflow.com/a/7636022/3186426)
我该怎么做??我错过了什么?
谢谢!
【问题讨论】:
-
这能回答你的问题吗? remove extra spaces in string javascript
标签: javascript reactjs whitespace trim removing-whitespace