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?

2

1 Answer 1

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.

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

1 Comment

Good answer:) Here 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:)

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.