With c# there is a string.Replace-method. Like This:
string oldString = "stackoverflow";
string newString= oldString.Replace("stackover","");
Output: flow
Can I do something similar to this with AngularJs?
My try doesn't work:
var oldString = "stackoverflow";
$scope.newString= oldString.Replace("stackover","NO");
Approach: The approach is utilizing the replace() method and replacing the content of the string with 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.
The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.
You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.
To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.
In Javascript method names are camel case, so it's replace
, not Replace
:
$scope.newString = oldString.replace("stackover","NO");
Note that contrary to how the .NET Replace
method works, the Javascript replace
method replaces only the first occurrence if you are using a string as first parameter. If you want to replace all occurrences you need to use a regular expression so that you can specify the global (g) flag:
$scope.newString = oldString.replace(/stackover/g,"NO");
See this example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With