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

Removing brackets around a string and placing contents into new object

本文关键字:新对象 对象 周围 字符串 删除      更新时间:2023-09-26

我有一个angular服务,它返回一个数组,里面有很多对象。

$ 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字段中看到它包含一个标题和一个位置。我怎样才能把标题和位置分开?同时移除括号吗?

服务:

$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不带标题

尝试:

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

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

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

您已经获得化学教师,您应该将其设置为标题而不是位置。

你可以这样做:

var regExp = /'(([^)]+)')/;
$scope.location = regExp.exec($scope.data[0].title);
$scope.data[0].title = $scope.data[0].title.replace(/'(.*?')/g,'');

应该根据需要更新标题和位置

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

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 strWithoutBracket = $scope.data[0].title.split((/'(([^}]+)')/)[1]));
console.log(strWithoutBracket);