Linebreak encoding (\ n) in Javascript alert ()



I need to make a replace in the string </script> by transforming it to 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 \n in the conversion of the code below?

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

See how the string is displayed by an alert after the 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!

asked by anonymous 17.09.2014 / 19:42

2 answers


Neither UTF-8 encoding nor ISO-8859-1 interferes with characters from 0x00 to 0x79, and this includes control characters such as tab, cr, lf, and so on. The problem with your code is the 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 like the "g" (global) flag passed as a string, but you can use the regex literal syntax to work around the problem:

str = str.replace( /\<\/script>/gi, "<br>\n" );
17.09.2014 / 20:26

I just got something like that, I solved by putting \n the first \ indicates that a special character will come next, in case only \n it tries to read n as a special character.

29.11.2016 / 11:45