Developer
Developer

Reputation: 2706

JavaScript split a string

Please see my JavaScript code:

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"]

Above code working fine. Every string split which has space. But I need to split above string like

1 = price  // Field name
2 = -a     // price type -a anonymous, -m model, -p private
3 = 20     // amount of price
4 = tips for model  //comment

Output should be

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

EDIT:

If i set limit of the split text. It looks like

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

N.B - Price type and comments are optional field. string may be /price 20 or /price 20 tips for model or /price -a 20 but price field is mandatory and must be a numeric value. Second field is optional it you will not entering any value. If you will entering any text except -a, -m, -p then this field validate.

Upvotes: 0

Views: 163

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382092

You don't need to split, but to extract parts, which can be done with a regular expression:

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

Result:

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

Now suppose that

  1. the string you get might be wrong,
  2. you want to ensure the third part is a number,
  3. the parameter -a or -e or -something is optional,
  4. the last part (the comments) is optional,

then you may use this:

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
}

Examples:

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

  • "/price -a 33.12" gives ["price", "-a", "33.12", ""]

Upvotes: 5

Pedro Lobito
Pedro Lobito

Reputation: 98861

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)


Output:

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

Upvotes: 0

Related Questions