How to Replace Control Characters in JavaScript

Tadashi Shigeoka ·  Thu, June 13, 2019

This article introduces sample code for replacing control characters in JavaScript.

JavaScript

Replacing Control Characters in JavaScript

Here’s sample code to replace all control characters in JavaScript:

/**
 * Replace control characters
 * 
 * @param {String} str
 * @param {String} [replacementStr]
 * @return {String} replaced string
 */
const replaceControlCharacters = (str, replacementStr = '') => {
  return str.replace(
    /[\\x00-\\x1F\\x7F-\\x9F]/g,
    replacementStr
  );
};

Here’s sample code that excludes only line feed characters from control characters:

/**
 * Replace control characters
 * 
 * The following control characters are excluded:
 * \\x0A LF
 * \\x0D CR
 *
 * @param {String} str
 * @param {String} [replacementStr]
 * @return {String} replaced string
 */
const replaceControlCharacters = (str, replacementStr = '') => {
  return str.replace(
    /[\\x00-\\x09\\x0B\\x0C\\x0E-\\x1F\\x7F-\\x9F]/g,
    replacementStr
  );
};

That’s all from the Gemba on replacing control characters in JavaScript.

Reference Information