Skip to content
Related Articles

Related Articles

How to replace a string by another string in AngularJS ?
  • Last Updated : 14 Oct, 2020

In this article, we will see how to select a string from the text and replace it by another string with the help of AngularJS.

Approach: The approach is to use the replace() method and replace the content of the string by the new one. In the first example the string ‘Welcome User‘ is replaced by the word ‘Geek‘ in place of ‘User‘. In the second example the word ‘User‘ is replaced by the string user enters in the input element.

Example 1:




<!DOCTYPE HTML>
<html>
  
<head>
    <script src=
"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">
    </script>
  
    <script>
        var myApp = angular.module("app", []);
        myApp.controller("controller", function ($scope) {
            $scope.str1 = "Welcome User";
            $scope.str2 = "";
            $scope.remSpaces = function () {
                $scope.str2 =
                    $scope.str1.replace("User", "Geek");
            };
        });
    </script>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
    <p>
        Replace a string by 
        another in AngularJS
    </p>
    <div ng-app="app">
        <div ng-controller="controller">
            String = '{{str1}}'<br><br>
            <button ng-click='remSpaces()'>
                Replace User
            </button>
            <br><br>
            Replaced String = '{{str2}}'<br>
        </div>
    </div>
</body>
  
</html>     

Output:



Example 2:




<!DOCTYPE HTML>
<html>
  
<head>
    <script src=
"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">
    </script>
  
<script>
        var myApp = angular.module("app", []);
        myApp.controller("controller", function ($scope) {
            $scope.str1 = "Welcome User";
            $scope.str2 = '';
            $scope.replaceStr = function () {
  
                // Get & replce the input value
                $scope.str1 = $scope.str1
                    .replace("User", $scope.str2);
  
            };
        });
    </script>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
    <p>
        Replace a string by 
        another in AngularJS
    </p>
    <div ng-app="app">
        <div ng-controller="controller">
            Enter here:
            <input type="text" 
                name="strExample" 
                ng-model="str2">
                  
            <br><br>
              
            <button ng-click='replaceStr()'>
                Replace</button><br><br>
            String = {{str1}}<br>
        </div>
    </div>
</body>
  
</html>

Output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :