Walentin Widgren
Walentin Widgren

Reputation: 63

How do I split a string, breaking at a word before a character?

I have the following string

'Material: Metall & PVC Size: Ø 32 mm Weight: 8 gram'

Using JavaScript, what is the fastest way to parse this into:

var title = ["Material:", "Size:", "Weight:"];
var property = ["Metall & PVC", "Ø 32 mm", "8 gram"];

Upvotes: 0

Views: 83

Answers (4)

fr3dgentil
fr3dgentil

Reputation: 31

var string = 'Material: Metall & PVC Size: Ø 32 mm Weight: 8 gram';
var title = string.match(/[^ ]+:/g);
var property = string.split(/ ?[^ ]+: ?/g).splice(1);
console.log(title, property);

Upvotes: 0

Geethu Jose
Geethu Jose

Reputation: 1993

To get the titles.

var string, titles;
string = 'Material: Metall & PVC Size: Ø 32 mm Weight: 8 gram';
titles = string.match(/[a-zA-Z]+:/g);
console.log(titles);

Use regular expression /[a-zA-Z]+:/g

To remove : from titles

var string, titles;
string = 'Material: Metall & PVC Size: Ø 32 mm Weight: 8 gram';
titles = string.match(/[a-zA-Z]+:/g);
for (var i = 0, len = titles.length; i < len; i++) {
  titles[i] = titles[i].slice(0, -1);
}
console.log(titles);

Upvotes: 1

Laposhas&#250; Acsa
Laposhas&#250; Acsa

Reputation: 1580

I know that regex is not cheap, and this will not work if you have spaces in your titles, but I think this can be a good starting point for you.

var string='Material: Metall & PVC Size: Ø 32 mm Weight: 8 gram';
var title=[], properties=[];
string.split(/(\w+:) /).forEach(function(element,index){
  if(index>0){// ignore first empty element
    if(index%2==1){
      title.push(element); // collect titles
    }else{
      properties.push(element); // collect properties
    }
  }
});

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68393

Try this

var regex = new RegExp(title.join("|"));
var input = 'Material: Metall & PVC Size: Ø 32 mm Weight: 8 gram';
var property = input.split( regex ).slice(-(title.length));

DEMO

var title = ["Material:", "Size:", "Weight:"];
var input = 'Material: Metall & PVC Size: Ø 32 mm Weight: 8 gram';

var regex = new RegExp(title.join("|"));
var property = input.split(regex).slice(-(title.length)).map( function(item){ return item.trim(); });

console.log(property);

Upvotes: 0

Related Questions