JavaScript split function

前端 未结 2 1222
情深已故
情深已故 2020-12-12 05:28

i like to split a string depending on \",\" character using JavaScript

example

var mystring=\"1=name1,2=name2,3=name3\";

need out

相关标签:
2条回答
  • 2020-12-12 05:51

    Just use string.split() like this:

    var mystring="1=name1,2=name2,3=name3";
    var arr = mystring.split(','); //array of ["1=name1", "2=name2", "3=name3"]
    

    If you the want string version of result (unclear from your question), call .join() like this:

    var newstring = arr.join(' '); //(though replace would do it this example)
    

    Or loop though, etc:

    for(var i = 0; i < arr.length; i++) {
      alert(arr[i]);
    }
    

    You can play with it a bit here

    0 讨论(0)
  • 2020-12-12 05:58
    var list = mystring.split(',');
    

    Now you have an array with ['1=name1', '2=name2', '3=name3']

    If you then want to output it all separated by spaces you can do:

    var spaces = list.join("\n");
    

    Of course, if that's really the ultimate goal, you could also just replace commas with spaces:

    var spaces = mystring.replace(/,/g, "\n");
    

    (Edit: Your original post didn't have your intended output in a code block, so I thought you were after spaces. Fortunately, the same techniques work to get multiple lines.)

    0 讨论(0)
提交回复
热议问题