-1

I need to convert a sub-string of a string with a character in javascript.

I used following code to do that

av_text_to_display = av_text_to_display.replace("a*^!", "'");

but it can only replace first occurrence. I used following code for all occurrences

av_text_to_display = av_text_to_display.replace("a*^!", "'", "g");

but it is not a standard way. What is the standard way to do that?

Joe Taras
  • 15,166
  • 7
  • 42
  • 55
user3384985
  • 2,975
  • 6
  • 26
  • 42
  • What is not standard? – Jongware Oct 26 '15 at 15:35
  • 2
    Possible duplicate of [Fastest method to replace all instances of a character in a string](http://stackoverflow.com/questions/2116558/fastest-method-to-replace-all-instances-of-a-character-in-a-string) – Joe Taras Oct 26 '15 at 15:35
  • Read the [docs for `replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace), and then please use regex instead of string literals. – Bergi Oct 26 '15 at 15:35
  • Possible duplicate of [Replacing all occurrences of a string in JavaScript](http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript) – James Oct 26 '15 at 15:40

3 Answers3

0

You are searching with a string instead of a RegExp, it should probably be:

av_text_to_display.replace(/a*\^!/g, "'");
axelduch
  • 10,769
  • 2
  • 31
  • 50
0

If you're trying to replace that literal string, and not a regex matching that string, use an escaped regex:

av_text_to_display = av_text_to_display.replace(/a\*\^!/g, "'");

var av_text_to_display = "here: a*^!, there: a*^! and also here, twice: a*^!a*^!";

av_text_to_display = av_text_to_display.replace(/a\*\^!/g, "'");

console.log(av_text_to_display);
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
0

If you don't want to use regex you can use the both split and join functions to do this :

your_string.split("a").join("'");

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101