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

javascript - React Native - how to trim a string - Stack Overflow

programmeradmin1浏览0评论

I want to delete the whitespaces from the beginning and the end of a string. For example, given a string " Test ", I would like to receive "Test". I have tried JavaScript's methods and also some npm libraries, but they don't seem to work with React Native? Any thoughts?

I want to delete the whitespaces from the beginning and the end of a string. For example, given a string " Test ", I would like to receive "Test". I have tried JavaScript's methods and also some npm libraries, but they don't seem to work with React Native? Any thoughts?

Share Improve this question edited Dec 12, 2016 at 8:43 Monika asked Dec 9, 2016 at 14:04 MonikaMonika 1891 gold badge1 silver badge9 bronze badges 4
  • " Test ".trim() ? – Pavneet_Singh Commented Dec 9, 2016 at 14:05
  • Are any errors being thrown? Where in the project are you calling this method? – Nader Dabit Commented Dec 9, 2016 at 14:14
  • 2 Try String.prototype.trim.call(your_str). – Allen Commented Dec 9, 2016 at 14:20
  • I use it like this: <TextInput ref="email" placeholder="E-mail" style={styles.input} onChangeText={email => this.setEmail({email})} /> . . . setEmail = (email) => { this.setState(email.trim(), function(){ this.validate(); }); } – Monika Commented Dec 12, 2016 at 8:42
Add a comment  | 

3 Answers 3

Reset to default 7

The problem is in your setEmail call and the ES6 syntax that you are using. When you do:

email => this.setEmail({email})

The transpiler transforms it into the following:

email => this.setEmail({email: email})

Which of course is an object.

Then, inside the function, you are trying to apply the trim function to an object, which of course results in failure. Try this instead:

email => this.setEmail(email)

You can read more on the ES6 syntax for object literals here.

In case the string you want to trim is a state and you want to trim the spaces, but not to render the whole page, then you can do it directly as following:

this.state.text = this.state.text.trim()

trim only cleans spaces. If you want to clean it all, including tabs, nbsp and so on, you can use this:

"\u2007 TEST \t\n".replace(/^\s+|\s+$/g, ""); // "TEST"
发布评论

评论列表(0)

  1. 暂无评论