[英]how to remove trailing and leading spaces from textbox input
if I have something like this:如果我有这样的事情:
return array.map(item => (
<input type="text" value={item.name}> onChange ={(name) => changeItemName(name.target.value)}
where the changeItemName function is basically a function that will change the name attribute of the current item.其中 changeItemName 函数基本上是一个将更改当前项目的名称属性的函数。 How can I go about making sure that the name attribute wont have any trailing or leading spaces?
我怎样才能确保名称属性不会有任何尾随或前导空格? I can do something like this in my changeItemName function:
我可以在我的 changeItemName 函数中做这样的事情:
changeItemName(name){
name.trim()
... logic to change name of item }
However since I am using onChange()
, this method is called everytime a character is typed.但是,由于我使用的是
onChange()
,因此每次键入字符时都会调用此方法。 This means that if a user types a regular space between 2 words, this wouldnt work because the name passed into the function would be trimmed thus now allowing any spaces.这意味着如果用户在 2 个单词之间键入常规空格,这将不起作用,因为传递给函数的名称将被修剪,因此现在允许任何空格。 How can I tweak this so that spaces still work but leading and trailing white spaces are gone?
我该如何调整它以使空格仍然有效但前导和尾随空格消失了?
You can trim the name
when the user finished typing.您可以在用户完成输入后修剪
name
。 For example when the input got out of focus.例如,当输入失去焦点时。 Try this:
尝试这个:
<input type="text" value={item.name}>
onChange ={(name) => changeItemName(name.target.value)}
onBlur={()=> { item.name = item.name.trim() }}
/>
Here the onBlur
function would fire when user goes to some other input or other part of your website.当用户转到您网站的其他输入或其他部分时,
onBlur
函数将在这里触发。
There are several options, one is to use a debouncing function that will trim the input after the user stops typing for a couple hundred milliseconds.有几种选择,一种是使用去抖动功能,该功能将在用户停止输入几百毫秒后修剪输入。 The other option is to trim the input on the blur event.
另一种选择是修剪模糊事件的输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.