删除字符串周围的括号并将内容放入新的 object

Removing brackets around a string and placing contents into new object

我有一个 angular 服务,其中 returns 一个数组,其中包含 objects 个数组。

$scope.data:

[
    {
        date: "03/12/2014",
        name: "mr blue",
        title: "math teacher (Germany)"
    },
    {
        date: "04/02/2015",
        name: "mrs yellow",
        title: "chemistry teacher (Spain)"
    },
]

从title字段可以看出它包含了一个title和一个location。我怎样才能分开标题和位置?同时删除括号?

服务:

$scope.loadFeed=function(e){        
    myService.parseFeed(url).then(function(res) {
        $scope.data = res.data.responseData.feed.entries;
    });
}

我试过的是:

$scope.loadFeed=function(e){        
    myService.parseFeed(url).then(function(res) {
        $scope.data = res.data.responseData.feed.entries;

        var strWithoutBracket = $scope.data[0].title.replace(/\(.*?\)/g,'');
        console.log(strWithoutBracket);

        $scope.location = strWithoutBracket;

    });
}

但是 console.log(strWithoutBracket); 显示为:

chemistry teacher

基本上我想要的是 $scope.title 没有位置。 $scope.location 没有标题。

以下是您可以尝试的方法。在下面的正则表达式中,我假设标题和方括号中的位置之间至少有一个空白字符。

var locationRegex = /\s+\(([a-zA-Z]*)\)*/;
var strWithoutBracket = $scope.data[0].title.replace(locationRegex,'');
var location = $scope.data[0].title.match(locationRegex)[1];

您可以使用这样的代码:

var str = "math teacher (Germany)";
var m = str.match(/(.*) *\((.*)\)/);
var obj = {
  title: m[1],
  location: m[2]
};
document.getElementById('output').innerHTML = JSON.stringify(obj);
<div id="output"></div>

试试这个

var strWithoutBracket = $scope.data[0].title.replace(/([()])+/g,'');

这是标题和位置的完整解决方案:

var str = "chemistry teacher (Spain)";

var regExp = /\(([^)]+)\)/;
var matches = regExp.exec(str);

var title = str.substring(0, str.indexOf('('));
var location = matches[1];

console.log('title : ' + title);
console.log('location : ' + location);

JSBin here

尝试:

$scope.data = [
    {
        date: "03/12/2014",
        name: "mr blue",
        title: "math teacher (Germany)"
    },
    {
        date: "04/02/2015",
        name: "mrs yellow",
        title: "chemistry teacher (Spain)"
    },
];

angular.forEach($scope.data, function(item){
    var values = /(.*)\s+\((.+)\)\s*$/.exec(item.title||"") || [];
    item.title = values[1];
    item.location = values[2];
});

console.log($scope.data);

Demo

您已经在聘请化学老师,您应该将其设置为职位而不是位置。

您可以执行以下操作:

var regExp = /\(([^)]+)\)/;
$scope.location = regExp.exec($scope.data[0].title);

$scope.data[0].title = $scope.data[0].title.replace(/\(.*?\)/g,'');

应根据需要更新您的标题和位置。

试试这个

var strWithoutBracket = $scope.data[0].title.split((/\(([^}]+)\)/)[1]));
console.log(strWithoutBracket);