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?

3
  • Instead of ${} use {{}} with your scope variables. Commented Jul 17, 2015 at 11:47
  • the URL actually comes back to me in a JS var that the server sends, hence why I'm trying to change the vars - those are placeholder tags sent Commented Jul 17, 2015 at 11:51
  • Okay. You'll have to do a replace like you did earlier except replace with your variable instead of a string. See the answer. Commented Jul 17, 2015 at 11:54

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

How would I update the two values together, would: $scope.newString = oldString.replace("\${cars}","\${color}",$scope.cars,$scope.color); work ok?
Work fine for my case.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.