21

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");
2
  • 1
    in javascript it is replace not Replace see your console for clues... Commented Aug 15, 2014 at 18:59
  • 2
    I rolled this back instead of deleting it - in this state the question and the answers all make sense, I'd rather do that than delete it. Commented Sep 20, 2014 at 5:18

3 Answers 3

56

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.

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

4 Comments

thanks for the answer. If I'm using a regular string it works. But I think something else is wrong, because my oldString is in Json and looks like this: [{"id":"RavenUsers/172"},{"id":"RavenUsers/173"},{"id":"RavenUsers/174"}] . Why doesn't it work on that?
I've seen the fiddle that it works. But I'm then trying to write it out in the html like this {{newString }} But it doesn't work.
@user3228992: When you edit your question, please don't remove all traces of the original question, it makes the answers look like they are answering some different queston (which they actually are...). What you have isn't a string, it's an array of objects. The response is deserialised from JSON by the $http.get method. You would need to loop through the items in the array and do the replace on the property in each object.
How to replace a comma with a new line?
5

The easiest way is:

var oldstr="Angular isn't easy";
var newstr=oldstr.toString().replace("isn't","is");

1 Comment

How to replace a comma with a new line?
1
var oldString = "stackoverflow";
var str=oldString.replace(/stackover/g,"NO");
$scope.newString= str;

It works for me. Use an intermediate variable.

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.