Ask Your Question

JavaScript evaluator: replace backslash

asked 2017-09-26 12:57:28 -0600

ruchir.nishkam gravatar image

updated 2018-01-31 10:50:18 -0600

metadaddy gravatar image

Is there a more sophisticated way of removing backslash within a string. Our team tried different ways javascript offers (replace, substr).

string in question: '\"Sending Timestamps\"'

string.replace(/\\/g, "") => does not help

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2017-09-26 19:57:18 -0600

metadaddy gravatar image

updated 2017-10-10 13:55:09 -0600

JavaScript replace returns a new string rather than modifying the string you call it on, so you need to do something like:

records[i] = records[i]\\/g,"");

image description

Note that if you are modifying field names rather than their values, you need to build a list of the old keys, a map of the new keys and their values, and then apply the changes. If you try to operate on the keys while looping through them, you'll get a ConcurrentModificationException.

For example, to remove backslashes from field names and values:

for(var i = 0; i < records.length; i++) {
  var record = records[i];
  try {    
    // Build an array of keys to be deleted,
    // and a map of new keys and values
    var oldkeys = [];
    var newvals = {};
    for (key in record.value) {
      newkey = key.replace(/\\/g,"");
      if (newkey != key) {
        newvals[newkey] = record.value[key].replace(/\\/g,"");        

    // Remove the old keys
    for (index in oldkeys) {

    // Add the new ones
    for (key in newvals) {
      record.value[key] = newvals[key];

    // Write record to processor output
  } catch (e) {
    // Send record to error
    error.write(record, e);

image description

edit flag offensive delete link more


Will the replace method work differently when changing keys ? '=\"Message Direction\"' :STRING ="FROM CLIENT" '\"Message Direction\"' :STRING "FROM CLIENT"

ruchir.nishkam gravatar imageruchir.nishkam ( 2017-09-27 11:40:50 -0600 )edit

Edited my answer to show how to do this

metadaddy gravatar imagemetadaddy ( 2017-10-10 13:55:21 -0600 )edit
Login/Signup to Answer

Question Tools

1 follower


Asked: 2017-09-26 12:57:28 -0600

Seen: 103 times

Last updated: Jan 31