Ask Your Question
1

JavaScript evaluator: replace backslash

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

ruchir.nishkam gravatar image

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

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
0

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

metadaddy gravatar image

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

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

records[i].value.name = records[i].value.name.replace(/\\/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) {
        oldkeys.push(key);
        newvals[newkey] = record.value[key].replace(/\\/g,"");        
      }
    }

    // Remove the old keys
    for (index in oldkeys) {
      record.value.remove(oldkeys[index]);
    }

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

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

image description

edit flag offensive delete link more

Comments

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 -0500 )edit

Edited my answer to show how to do this

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

Question Tools

1 follower

Stats

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

Seen: 279 times

Last updated: Jan 31