Search code examples
javascriptregexangularjsangular-servicesangular-filters

Removing brackets around a string and placing contents into new object


I have an angular service which returns an array with a number of objects inside.

$scope.data:

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

You can see from the title field it contains a title and a location. How can i separate the title and location? Whilst removing the brackets too?

Service:

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

What i have tried is:

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

    });
}

However console.log(strWithoutBracket); is displaying as:

chemistry teacher

Essentially what i am after is a $scope.title without the location. And $scope.location without the title.


Solution

  • Here is a complete solution for title and location :

    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