How to Split string with multiple rules in javascript

后端 未结 5 820
终归单人心
终归单人心 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:31

    This works:

    array = string.replace(/#|\./g, ' &$&').split(' ');
    

    Take a look at demo here: http://jsfiddle.net/M6fQ7/1/

    0 讨论(0)
  • 2021-01-25 03:35

    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("#", "&#") and str.replace(".","&.") when you find

    0 讨论(0)
  • 2021-01-25 03:36

    I would think a combination of split() and replace() is what you are looking for:

    str = "my name is john#doe oh.yeh";
    
    strArr = str.replace('\W',' &');
    
    strArr = strArr.split(' '); 
    

    That should be close to what you asked for.

    0 讨论(0)
  • 2021-01-25 03:40

    You have to use a Regular expression, to match all special characters at once. By "special", I assume that you mean "no letters".

    var pattern = /([^ a-z]?)[a-z]+/gi;             // Pattern
    var str = "my name is john#doe oh.yeh";         // Input string
    var strArr = [], match;                         // output array,  temporary var
    while ((match = pattern.exec(str)) !== null) {  // <-- For each match
       strArr.push( (match[1]?'&':'') + match[0]);  // <-- Add to array
    }
    // strArr is now:
    // strArr = ['my', 'name', 'is', 'john', '&#doe', 'oh', '&.yeh']
    

    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.

    0 讨论(0)
  • 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+/)
    
    0 讨论(0)
提交回复
热议问题