删除字符串周围的括号并将内容放入新对象中
Removing brackets around a string and placing contents into new object
我有一个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);
相关文章:
- javascript处理一个对象数组以获得一个新的对象数组
- 返回带有筛选结果的新JSON对象
- 新Javascript对象的可选初始化属性
- Kinetic.js旋转组对象的新子对象具有不正确的偏移
- 嵌入多对多关系-如果一个新对象还不存在,则添加一个新的对象
- Jquery新元素在连接时导致[对象对象]
- 传递 JavaScript 函数以在新窗口对象中运行
- 单击新 DOM 对象时的操作
- 使用 JavaScript 比较 2 个数组并创建一个新的对象数组,该数组不包含与 id 字段匹配的对象
- 使用对象方法实例化新的对象 JavaScript
- 如何在使用 outerHTML 更改内容后获取对新 DOM 对象的引用
- 如何将两个 JS 数组连接到一个新的对象数组作为键:值
- 来自String的Javascript新Date对象,IE和FF上的不同结果
- 创建新日期对象时不一致
- 将对象的值推送到新的对象数组中
- 为 AJAX 数据添加新的对象值
- 无法使用新数据对象更新Knockout UI
- 通过比较和推送唯一对象来创建新的对象数组
- 如何在javascript中添加新的对象类型
- 我如何过滤对象并获得一个新的对象