2

I want to replace the character { and } in a html string to {{ and }} i am using the replace function but i have the following error :

$scope.selectedtemplate.template.replace  is not a  function

My code

 $scope.selectedtemplate.template = $scope.selectedtemplate.template.replace("{" , "{{" ) ;
 $scope.selectedtemplate.template = $scope.selectedtemplate.template.replace("}" , "}}" ) ;

template is the HTML string

3
  • 1
    Apparently it's not an HTML string, as otherwise it would have a .replace method. Make sure the property really contains the value you expect at that time. Commented Sep 8, 2015 at 19:45
  • should have null check first and then do .replace string. Commented Sep 8, 2015 at 19:46
  • No isn't null was an object , i converted the object to string but don't replace the character. Commented Sep 8, 2015 at 20:41

2 Answers 2

3

Here is an example: http://fiddle.jshell.net/33tom882/2/

You are probably getting the "replace is not a function" error because $scope.selectedtemplate.template is undefined or is not type of string. See here for more info on the string.replace function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

It seems like there would be a better way to solve your actual issue though, which would be to use Angular $scope properties to manage your variables rather than directly modifying the HTML as a string.

Sign up to request clarification or add additional context in comments.

Comments

2

There are two issues with yore code:

  • you need to convert template to a string before manipulating it as a string

  • you should replace the character globaly:

    $scope.selectedtemplate.template = $scope.selectedtemplate.template.toString().replace(/{/g , "{{" ) ;
    $scope.selectedtemplate.template = $scope.selectedtemplate.template.toString().replace(/}/g , "}}" ) ;
    

2 Comments

what if template is null/undefined?
the code above should apparently be wrapped with a if

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.