1

My URL structure:

/json/feed?car=${cars}&colour=${color}&model=VW

I want to replace what is in ${} with JavaScript var's I have available (var cars, var colors, etc.), however I am not sure how I can do this easily with Angular.

Would something like:

$scope.newString = oldString.replace("${cars}","cars");

Work ok, or is there a %s way of doing this with JavaScript ? Which is a better way with Angular?

galath
  • 5,717
  • 10
  • 29
  • 41
Poiro
  • 951
  • 4
  • 10
  • 20

2 Answers2

2

Replace with variable instead of string.

$scope.newString = oldString.replace("${cars}",$scope.cars);

Please take a look at this plunkr for reference.

You can simply chain .replace's.

$scope.new = old.replace('${cars}', $scope.car).replace('${color}', $scope.color).replace('${model}', $scope.model);
Raphael Rafatpanah
  • 19,082
  • 25
  • 92
  • 158
2

http://plnkr.co/edit/cFeD3tLOYWcPVwMAFQG3?p=preview

How to replace all occurrences of a string in JavaScript?

You can use interpolate service of angularjs. Interpolate service works with angular js expressions, which should consist {{ }} instead of {} for replacement.

app.controller('MainCtrl', function($scope,$interpolate) {
  $scope.name = 'World';

  function escapeRegExp(string) {
    return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
  function replaceAll(string, find, replace) {
    return string.replace(new RegExp(escapeRegExp(find), 'g'), replace);
  }

  $scope.interpolate = function ( ) {
    var context = { cars :"myCars", color:"red"};
    var url = "/json/feed?car=${cars}&colour=${color}&model=VW";
    var t1 = replaceAll(url,"{","{{");
    var url2 = replaceAll(t1,"}","}}");
    var exp = $interpolate(url2);
    console.log(exp(context)); 
  }

  $scope.interpolate();
});

Output : /json/feed?car=$myCars&colour=$red&model=VW

Community
  • 1
  • 1
adt
  • 4,320
  • 5
  • 35
  • 54