Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.Replace in AngularJs

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");
like image 509
user3228992 Avatar asked Aug 15 '14 18:08

user3228992


People also ask

How to change string in AngularJS?

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.

How do I replace a character in a string?

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.

How do you replace a letter in a string JavaScript?

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.

How do you replace all occurrences of a character in a string in JavaScript?

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.


1 Answers

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.

like image 133
Guffa Avatar answered Sep 18 '22 11:09

Guffa