JavaScript拆分字符串

时间:2015-05-04 11:44:52

标签: javascript split

请参阅我的JavaScript代码:

var str = "/price  -a 20 tips   for model";
var removeSlsh = str.slice(1); //output = price  -a 20 tips   for model
var newStr = removeSlsh.replace(/\s+/g,' ').trim().split(' ');
console.log(newStr); // Output = ["price", "-a", "20", "tips", "for", "model"]

以上代码正常工作。每个字符串分裂,有空格。但是我需要像

一样拆分字符串
1 = price  // Field name
2 = -a     // price type -a anonymous, -m model, -p private
3 = 20     // amount of price
4 = tips for model  //comment

输出应为

["price", "-a", "20", "tips for model"]

修改

如果我设置了分割文本的限制。它看起来像

var newStr = removeSlsh.replace(/\s+/g,' ').trim().split(' ',4);
console.log(newStr); // Output = ["price", "-a", "20", "tips"]

N.B - 价格类型和评论是可选字段。字符串可以是/price 20/price 20 tips for model/price -a 20,但价格字段是必填字段,必须是数字值。第二个字段是可选的,您不会输入任何值。如果您要输入除-a, -m, -p之外的任何文本,则此字段将验证。

2 个答案:

答案 0 :(得分:4)

您不需要拆分,而是提取部件,这可以使用正则表达式完成:

var parts = str.match(/^\/(\S+)\s+(\S+)\s+(\S+)\s*(.*)/).slice(1);

结果:

["price", "-a", "20", "tips   for model"]

现在假设

  1. 你得到的字符串可能是错的,
  2. 你想确保第三部分是一个数字,
  3. 参数-a或-e或-something是可选的,
  4. 最后一部分(评论)是可选的,
  5. 然后你可以用这个:

    var m = str.match(/^\/(\S+)(\s+-\w+)?\s+(-?\d+\.?\d*)\s*(.*)/);
    if (m) {
        // OK
        var parts = m.slice(1); // do you really need this array ?
        var fieldName = m[1]; // example: "price"
        var priceType = m[2]; // example: "-a" or undefined
        var price = +m[3];    // example: -23.41
        va comments = m[4];   // example: "some comments"
        ...
    } else {
       // NOT OK
    }
    

    示例:

    • "/price -20 some comments"提供["price", undefined, "-20", "some comments"]

    • "/price -a 33.12"提供["price", "-a", "33.12", ""]

答案 1 :(得分:0)



var str = "/price  -a 20 tips   for model";
str = str.replace(/\//g,'').replace(/\s+/g,' '); //removes / and multiple spaces
var myregexp = /(.*?) (.*?) (.*?) (.*)/mg; // the regex 
var match = myregexp.exec(str).slice(1); // execute the regex and slice the first match
alert(match)




输出:

 ["price", "-a", "20", "tips for model"]