string to object in javascript

2

I'm getting an object as a parameter, eg "4,5" from a function, but I need to change the comma by one point. Qnd I do this, the object is changed to string, so I need to return that string to object again. I'm trying to get the following code:

var teste = JSON.stringify(editableObj.innerHTML);
teste = teste.replace(/\,/g, '.');
var obj = JSON.parse(teste);
alert(typeof(obj));
    
asked by anonymous 24.06.2016 / 19:10

1 answer

1

The value in editableObj.innerHTML does not return an object, whenever a HTML value is taken through innerHTML , the return is always string . To confirm this type alert(typeof(editableObj.innerHTML)) .

editableObj is the object that represents your element, if you convert the object to string to make the changes your code would look like.

var teste = JSON.stringify(editableObj); // passa o Object HTML para string
teste = teste.replace(/\,/g, '.');
var obj = JSON.parse(teste); //Retorna o objeto
alert(typeof(obj));

Now if you just want to replace , with . , you do not need JSON .

var teste = editableObj.innerHTML.replace(/\,/g, '.');
editableObj.innerHTML = teste;
alert(typeof(teste));

// string
    
24.06.2016 / 20:22