Line break encoding ( n) in Javascript Alert()

Asked

Viewed 19,648 times

7

Hello,

I need to replace the string </script> transforming it into the string \n. The problem is that unfortunately my PHP project is with charset=ISO-8859-1, while javascript runs with UTF8.

What code or character can I use to represent the \n in the code conversion below?

str = str.replace(/\<\/script>/g, encodeURIComponent(String("\n")));

See how the string is displayed by an Alert after conversion?

Erro ao enviar email. %5CnErro ao enviar email. %5CnO seu chamado foi cadastrado com sucesso! 

And how I wanted it to be printed:

Erro ao enviar email. 
Erro ao enviar email. 
O seu chamado foi cadastrado com sucesso! 

Thank you!

2 answers

8


Neither UTF-8 nor ISO-8859-1 encoding interferes with characters from 0x00 to 0x79, and this includes control characters such as tab, cr, lf and others. The problem with your code is incorrect use of str.replace.

Here are some possible solutions, depending on the desired result:

str = str.replace("</script>", "\n", "g" );
str = str.replace("</script>", "<br>\n", "g" );

// Se preferir trocar tanto `</script>` quanto `</SCRIPT>` e outras combinações,
// acrescente a flag `i`:
str = str.replace("</script>", "<br>\n", "gi" );

Some browsers do not sympathize with the "g" (global) flag passed as string, but it is possible to use syntax with regex literal to get around the problem:

str = str.replace( /\<\/script>/gi, "<br>\n" );
  • Thank you @Bacco. The example worked perfectly for me.

0

I just picked up something similar, I solved it by putting \\n the first \ indicates that there will be a special character then in case only \n he tries to read n as a special character.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.