1

I have a string coming to my WebApp formatted this way:

GPL.TU01<50;0;100;0;0>

I have to out put it this way:

GPL.TU01
<
50;
0;
100;
0;
0
>

This is what I'm using:

var GET_result_formatted = GET_result;
global_file_content = GET_result;
GET_result_formatted = GET_result_formatted.replace("<", "\r<\r");
GET_result_formatted = GET_result_formatted.replace(';', ";\r");
GET_result_formatted = GET_result_formatted.replace(">", "\r>");
$('#ModalGPLTextarea').val(GET_result_formatted);

But the sad result is this:

GPL.TU01
<
50;
0;100;0;0
>

What am I doing wrong?

Mr.Web
  • 6,992
  • 8
  • 51
  • 86
  • You need to use regex for String.replace for replacing multiple instances. – risyasin Nov 18 '15 at 12:06
  • 3
    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 Thorpe Nov 18 '15 at 12:07

1 Answers1

8

.replace only replaces the first occurrence, when a string is passed.
Use a regex instead, for the ;:

GET_result_formatted = GET_result_formatted.replace("<", "\r<\r");
GET_result_formatted = GET_result_formatted.replace(/;/g, ";\r");
GET_result_formatted = GET_result_formatted.replace(">", "\r>");

The g in /;/g is a "global" flag, that means it will replace all occurrences of ;.


These lines can also be shortened a lot, since .replace can be chained:

var GET_result_formatted = GET_result.replace("<", "\r<\r")
                                     .replace(/;/g, ";\r")
                                     .replace(">", "\r>");
global_file_content = GET_result;
$('#ModalGPLTextarea').val(GET_result_formatted);

Notice the missing ; at the end of the first 2 lines.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • Good answer:) [Here](http://jsmantras.com/blog/String-Methods-search-match-and-replace) is some more stuff on `.replace` and other string methods. Sorry to be a bother, I started on my own answer, but it would've been almost an exact copy of your answer. Do you mind adding something to your answer about `.split` then `.join`? Personally I have seen faster results doing that rather than a `.replace`:) – tkellehe Nov 18 '15 at 12:34