javascript用特殊字符分割字符串 [英] javascript splitting a string at special character
问题描述
我试图智能地预先填写表格,我想根据用户的电子邮件地址预先填写名字和姓氏输入,例如,
I am trying to "intelligently" pre-fill a form, I want to prefill the firstname and lastname inputs based on a user email address, so for example,
jon.doe@email.com返回Jon Doe
jon_doe@email.com返回Jon Doe
jon-doe@email.com返回Jon Doe
jon.doe@email.com RETURNS Jon Doe
jon_doe@email.com RETURN Jon Doe
jon-doe@email.com RETURNS Jon Doe
我设法在 @
之前获取了字符串,
I have managed to get the string before the @
,
var email = letters.substr(0, letters.indexOf('@'));
但是当分隔符可以是多个值时,无法解决split()的问题,我可以这样做,
But cant work out how to split() when the separator can be multiple values, I can do this,
email.split("_")
但是如何在其他电子邮件地址上分割有效的特殊字符?
but how can I split on other email address valid special characters?
推荐答案
JavaScript的字符串 split
方法可以使用正则表达式。
JavaScript's string split
method can take a regex.
例如,以下内容将在上分割。
,-
和 _
。
For example the following will split on .
, -
, and _
.
"i-am_john.doe".split(/[.\-_]/)
返回以下内容。
["i", "am", "john", "doe"]
这篇关于javascript用特殊字符分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!