I have such strings which are received from a .pck
file:
'{"aaa":"sssbbb"}'
'{"aaa":"ssscde"}'
I need to delete everything after the backslash (including the backslash) till the first "
, respectively till the end of current value. So, I expect this result for both of those strings:
'{"aaa":"sss"}'
'{"aaa":"sss"}'
I can’t really parse this and can’t really string replace the backslash with anything else. I have tried to get the index of the backslash using str.indexOf("\");
, but got -1
. I have tried lots of regex expressions, but did not work. I have tried to replace str.replace(String.charCodeAt(92))
, but did not work either.
Tonu Lucian is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
18
You can pass a reviver function to correct the values upon parsing.
const reviverFn = (key, value) => {
if (typeof value !== 'string') return value;
return value.split('\')[0];
};
const parseJSON = (jsonStr) => JSON.parse(
jsonStr.replace(/\/g, '\\'), // Need to double-up for valid JSON
reviverFn); // Use the reviver function
const parsed = parseJSON('{"aaa":"sss\bbb"}');
console.log('Parsed:', parsed); // { aaa: "sss" }
console.log('Serialized', JSON.stringify(parsed));
.as-console-wrapper { top: 0; max-height: 100% !important; }
You can use a regular expression to match the portion of the string you want to remove.
Example:
#original string
let str = ‘{“aaa”:”sssbbb”}’;
// Regular expression to match the backslash and everything after it
let updatedStr = str.replace(/[^”,]*/g, ”);
// Output the updated string
console.log(updatedStr);