简体   繁体   中英

Escape special characters in a String

I have a String: c:\\build\\target .

This comes from an external source, passed directly as it is. I cannot modify it before using it in a javascript.

However \\b and \\t are special characters, but I'd simply like to print it (or work with it) as it looks like, not as it is interpreted c:uild arget .

How is it possible?

You could try:

string = "c:\build\target";
string = string.replace(/[\n]/g,'\\n');
string = string.replace(/[\r]/g,'\\r');
string = string.replace(/[\t]/g,'\\t');
string = string.replace(/[\b]/g,'\\b');
string = string.replace(/[\f]/g,'\\f');
console.log(string);​

But there maybe some other problems, because you have to catch all the other special chars

Using a single regex replace (instead of many) is quicker and avoids errors related to the replace order.

console.info('c:\build\target'); // cuild   arget

console.info(escape('c:\build\target')); // c:\build\target

function escape(str) {
  return str.replace(/[\b\f\n\r\t\v\0\'\"\\]/g, match => {
    return {
      '\b': '\\b',
      '\f': '\\f',
      '\n': '\\n',
      '\r': '\\r',
      '\t': '\\t',
      '\v': '\\v',
      '\0': '\\0',
      '\'': '\\\'',
      '\"': '\\\"',
      '\\': '\\\\'
    }[match]
  })
}

The simplest way would be to escape every backslash (so it's interpreted as a literal backslash).

If you can't do this on the remote system itself, you'll need to do this as the data is being parsed in Javascript. Obviously once you already have a Javascript string, the backslashes are already missing.

So at the point where you go from "remote string" (which includes a \\ character followed by a b ) to "Javascript string" (which includes a \\b unprintable character), you'll need to keep an eye out for backslashes. And ensure they're passed through as a literal backslash (ie escaped), rather than as an escape prefix.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM