如何在javascript中使用多个规则分割字符串
例如,我有这个字符串:
str = "my name is john#doe oh.yeh";
我正在寻找的最终结果是这个数组:
strArr = ['my','name','is','john','&#doe','oh','&yeh'];
这意味着适用 2 条规则:
- 在每个空格“”之后分割(我知道如何)
- 如果有特殊字符(“.”或“#”) ) 然后也拆分但添加字符“&”在带有特殊字符的单词之前。
我知道我可以 strArr = str.split(" ") 作为第一条规则。但我该如何做另一个技巧呢?
谢谢, 阿隆
I have this string for example:
str = "my name is john#doe oh.yeh";
the end result I am seeking is this Array:
strArr = ['my','name','is','john','doe','oh','&yeh'];
which means 2 rules apply:
- split after each space " " (I know how)
- if there are special characters ("." or "#") then also split but add the characther "&" before the word with the special character.
I know I can strArr = str.split(" ") for the first rule. but how do I do the other trick?
thanks,
Alon
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
假设结果应该是
'&doe'
而不是'&#doe'
,一个简单的解决方案是替换所有.
和#
与&
以空格分隔:/\s+/
匹配连续的空格而不是仅一个。如果结果应为
'&#doe'
和'&.yeah'
使用相同的正则表达式并添加捕获:Assuming the result should be
'&doe'
and not'&#doe'
, a simple solution would be to just replace all.
and#
with&
split by spaces:/\s+/
matches consecutive white spaces instead of just one.If the result should be
'&#doe'
and'&.yeah'
use the same regex and add a capture:您必须使用正则表达式来一次匹配所有特殊字符。通过“特殊”,我认为你的意思是“没有字母”。
它不匹配连续的特殊字符。为此必须修改模式。例如,如果要包含所有连续字符,请使用
([^ az]+?)
。此外,它不包含最后一个特殊字符。如果您也想包含此内容,请使用
[az]*
并删除!== null
。You have to use a Regular expression, to match all special characters at once. By "special", I assume that you mean "no letters".
It does not match consecutive special characters. The pattern has to be modified for that. Eg, if you want to include all consecutive characters, use
([^ a-z]+?)
.Also, it does nothing include a last special character. If you want to include this one as well, use
[a-z]*
and remove!== null
.使用 split() 方法。这就是你需要的:
http://www.w3schools.com/jsref/jsref_split.asp
好的。我看到了,你找到了,我想:
1)首先使用拆分到空格
2) 迭代数组,当找到 # 或 时再次拆分数组成员。
3) 再次遍历数组,然后
str.replace("#", "&#")
和str.replace(".","&.")
当你发现use split() method. That's what you need:
http://www.w3schools.com/jsref/jsref_split.asp
Ok. i saw, you found it, i think:
1) first use split to the whitespaces
2) iterate through your array, split again in array members when you find # or .
3) iterate through your array again and
str.replace("#", "&#")
andstr.replace(".","&.")
when you find我认为 split() 和 Replace() 的组合就是您正在寻找的:
这应该接近您的要求。
I would think a combination of split() and replace() is what you are looking for:
That should be close to what you asked for.
这有效:
在此处查看演示:http://jsfiddle.net/M6fQ7/1/
This works:
Take a look at demo here: http://jsfiddle.net/M6fQ7/1/