如何在javascript中拆分包含多个规则的字符串 [英] How to Split string with multiple rules in javascript
本文介绍了如何在javascript中拆分包含多个规则的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个字符串例如:
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'];
这意味着适用2条规则:
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.
我知道我可以strArr = str.split()第一条规则。但我该如何做其他伎俩?
I know I can strArr = str.split(" ") for the first rule. but how do I do the other trick?
谢谢,
Alon
thanks, Alon
推荐答案
假设结果应为'& doe'
而不是'& #doe'
,一个简单的解决方案就是用& 替换所有
。
和#
code>按空格分割:
Assuming the result should be '&doe'
and not '&#doe'
, a simple solution would be to just replace all .
and #
with &
split by spaces:
strArr = str.replace(/[.#]/g, ' &').split(/\s+/)
/ \s + /
匹配连续的空格而不是一个。
/\s+/
matches consecutive white spaces instead of just one.
如果结果应为'& #doe'
和'& .yeah'
使用相同的正则表达式并添加捕获:
If the result should be '&#doe'
and '&.yeah'
use the same regex and add a capture:
strArr = str.replace(/([.#])/g, ' &$1').split(/\s+/)
这篇关于如何在javascript中拆分包含多个规则的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文