How to handle newline codes when outputting JS strings in PHP

When outputting data from PHP to work with JavaScript, line feed codes in the data can cause errors in JavaScript. This problem is often especially pronounced when outputting strings as JSON data or variables.

The following is an example of retrieving a store address from a WordPress custom field and using it in JavaScript.

echo str_replace(array("rn", "r", "n"), '', get_field('hoge'));

This code removes the newline codes ( rn, r, n ) from the string obtained with get_field('hoge'). This avoids errors in JavaScript because the output string does not contain newlines.

However, there are several other possible approaches to solving the problem besides this method. For example, you can encode the data in JSON format or use PHP’s json_encode function.

Which method you choose depends on the situation and the technology you are using, so choose the appropriate method.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top