如何拆分字符串,在字符前突破单词?

时间:2017-04-12 07:00:06

标签: javascript split

我有以下字符串

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

使用JavaScript,解析它的最快方法是:

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

4 个答案:

答案 0 :(得分:1)

获得标题。

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

使用正则表达式/[a-zA-Z]+:/g

从标题中删除:

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);

答案 1 :(得分:0)

试试这个

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));

<强>样本

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);

答案 2 :(得分:0)

我知道正则表达式不便宜,如果你的标题中有空格,这将不起作用,但我认为这对你来说是一个很好的起点。

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
    }
  }
});

答案 3 :(得分:0)

&#13;
&#13;
extension UIViewController {
  func showAlert(title: String, message: String) {
    let alertController = UIAlertController(title: title, message:
      message, preferredStyle: .alert)
    alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: {action in
    }))
    self.present(alertController, animated: true, completion: nil)
  }
}
&#13;
&#13;
&#13;