How to Split string with multiple rules in javascript

后端 未结 5 827
终归单人心
终归单人心 2021-01-25 03:18

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         


        
5条回答
  •  臣服心动
    2021-01-25 03:52

    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+/ matches consecutive white spaces instead of just one.

    If the result should be '&#doe' and '&.yeah' use the same regex and add a capture:

    strArr = str.replace(/([.#])/g, ' &$1').split(/\s+/)
    

提交回复
热议问题