How to find special characters that are inside other characters using javascript

3

I have a string value in json format '{"text": "Look" I "here"}' and that I want to change this quote "I" because it will give error in the code. I was thinking of using JSON.parse and looping in the items, but the JSON function does not run because of the error, why can not use the same type of start and end quotes within the string except to mention a function or var.

I think you can do this by using replace to replace the quotation marks inside the quotation marks.

    
asked by anonymous 12.04.2014 / 11:29

2 answers

3

As a brasophile in the comments , the ideal is to prevent this wrong string from entering JSON in the first place. Dealing with the problem after the fact is much more difficult ...

If your JSON has exactly this format, just take everything inside the string and do a replace:

var string = '{"text": "Olha "eu" aqui"}';
var prefixo = '{"text": "';
var sufixo = '"}';

var conteudo = string.substring(prefixo.length, string.length-sufixo.length);

var novaString = prefixo + conteudo.replace(/"/g, '\"') + sufixo;

If you do not have it, you're having problems ... How to interpret the string below?

{"text":"b","c":"d"}
  • Key: text , value: b ; key: c , value d ? or:
  • Key: text , value: b","c":"d ?
  • That is, the only correct solution is to deal with the problem before the string stops at JSON. If you have, for example, a legacy file where - for a bug - the format went wrong that way, you can even use an automated process to help you fix it, but you have to review it by hand ... Now, if it is an existing code that is generating this type of string, this code is bugged and you should correct it in source - and not apply a "band aid" ...

        
    12.04.2014 / 12:55
    1

    If you change all "eu" is easy:

    var string = '{"text": "Olha "eu" aqui"}';
    var stringLimpa = string.replace('"eu"', 'eu');
    

    If you want to change the entire contents of text then you can test this:

    var string = '{"text": "Olha "eu" aqui"}';
    var conteudo = string.match(/{"text": "(.*)"}/)[1]; // criar um string com o conteudo
    string = string.replace(conteudo, conteudo.replace(/"/g, '\'')); // subtituir o conteudo por novo conteudo com ' em vez de "
    console.log(string); // {"text": "Olha 'eu' aqui"}  // só para confirmar
    
    var json = JSON.parse(string);
    console.log(json); // Object {text: "Olha 'eu' aqui"} 
    

    Example

    Simplifying , and putting it in a function:

    function limpar(s) {
        var conteudo = s.match(/{"text": "(.*)"}/)[1];
        var conteudoLimpo = conteudo.replace(/"/g, '\'');
        s = s.replace(conteudo, conteudoLimpo);
        return JSON.parse(s);
    };
    
    var string = '{"text": "Olha "eu" aqui"}';
    var objeto = limpar(string);
    

    Example

        
    12.04.2014 / 12:15