javascript object value to string conversion - javascript

I am getting the value of input using javascript using below code.
var name=document.getElementById("firstName").value;
Getting output like rk-chaitu.I want to split this output using reg expression.
Now my question is how to convert name object to String?
Regards,
Chaitu

name should already be a string. You can directly use name.split(separator).
EDIT: I see you have added information. Can you post more code? Perhaps the error comes from something else.

The value attribute should already be a String.

Related

Why is the browser changing my single quotes to double and ruining my JSON in the data attr?

This should be way easier than it is, but it's got me stuck.
Im putting some JSON in an input data attribute and the quotes on the first key are closing the attribute.
Here's what I'm trying to do:
var html = `<input type="checkbox" data-values='${dataVals}' />`;
Where dataVals is a JSON string like this
'{"checked":true,"unchecked":false}'
But it's showing up in the browser like this:
<input type="checkbox" data-values="{"checked":true,"unchecked":false}">
And the browser is reading it essentially as though it's this.
data-values="{"
Which obviously isn't what I want.
I'm clearly missing something. Any thoughts?
Combination of #T.J. Crowder and #Teemu
I added a replace at the end of the json string to replace double quotes with "
JSON.stringify({ ... }).replace(/\"/g, """)
Then also stopped trying to run JSON.parse() when I wanted to get the value later since $.data('values') already returns a javascript object (when it can).
JSON.parse($(this).data('values')) => $(this).data('values')

Setting an element value using HTML entities

I'm having an issue trying to set an input field's value when using HTML entities in that they are coming out literally as " rather than ".
Here is the code I am using:
document.getElementById('inputSurname').setAttribute('value', 'test"""');
in which the output is test""" though I want the output to be test""".
It doesn't look like a double-encoding issue since in the source code I am seeing it the same way I have set it here.
I know I could decode the value from its HTML entity format though this is something I want to avoid if possible for security.
Any help would be much appreciated :)
Try this:
document.getElementById('inputSurname').value = 'test"""';
Or if you want to keep &quot:
function myFunction() {
document.getElementById('myText').value = replaceQuot('test&quot&quot&quot');
}
function replaceQuot(string){
return string.replace('&quot', '""');
}
Or you can use escape characters.
document.getElementById("inputSurname").setAttribute("value", "test\"\"\"\"");
Well you could just write the new value as 'test"""'.
For other characters however, I'm going to refer you to this answer: HTML Entity Decode

Parsing JSON with spaces in key name with AngularJS

I have a json which has spaces in key names.
The JSON has the following format
{
"response":{"docs":[
{
"my name":"krammer",
"job": "stackexchange"
}
}
}
While using ng-repeat to get the parameters into a list, I use the following code
{{friends.['my name']}}
But this gives an empty output. While
friends.my name
gives an error.
So how can the key names with empty spaces be accessed using AngularJS ?
Please try this
{{friends['my name']}}
It doesn't have anything to do with angular, this is the way we read props from JavaScript object, here you have a object called friends. so these are all we can do, if we don't have invalid javascript characters for naming in JavaScript, like space and some other:
friends.myname
friends['myname']
friends["myname"]
but when we have those invalid characters we only can do:
friends['my name']
friends["my name"]
You may run into a case where {{friends['my name']}} does not work. If so, try the following:
{{friends.my_name}}
{{friends['my name']}} will be working fine

Extracting values with Javascript

I have a variable called "result",
var result;
that result value is equal to following value, please presume that is just a string :)
---------result value -----------
for (;;);{
"send":1,
"payload":{
"config":{
"website":"",
"title":"welcome to site",
"website-module":1313508674538,
"manufatureid":"id.249530475080015",
"tableid":"id.272772962740259",
"adminid":100002741928612,
"offline":null,
"adminemail":"admin#website.com",
"adminame":"George",
"tags":"web:design:template",
"source":"source:design:web",
"sitelog":[],
"errorlog":0,
"RespondActionlog":0,
"map":null
},
"imgupload":""
},
"criticalerror":[0],
"report":true
}
---------result value------------
From that value, I would like to extract tableid which is "id.272772962740259" with classic Javascript.
How can I extract the code, please let me know how can i do with simple javascript, please don't use Jquery, all I just need is simple javascript.
You can simply evaluate the value of the variable to obtain the values. However, please note that your current value is not valid JSON; that for(;;); at the beginning of the value invalidates the format. Remove that, and you can do this:
var object = eval('(' + resultMinusThatForLoop + ')');
alert(object.payload.config.tableid);
If that data is a string the parse it with a JSON parse. The following should get the value you want
JSON.parse(result).payload.config.tableid; // "id.272772962740259"
Edit: though, as Tejs says, the for(;;) invalidates the string and stops it from being parsed. If you can remove that, do.
You need to remove the empty for loop, then parse the string. DO NOT use eval; most modern browsers provide built-in JSON-parsing facilities, but you can use json2.js if yours does not. Assuming that you assign the results of parsing the JSON to result, you should be able to get that value using result.payload.config.tableid.
You should probably read a good JS reference. JavaScript: The Good Parts or Eloquent JavaScript would be a good choice.
If result is a javascript object and not a string, you can just use 'result.payload.config.tableid'.
If it is not, how do you get the AJAX result? Are you using XmlHttpRequest directly? Most libraries will give you a javascript object, you might be missing a flag or not sending the response back with the right content type.
If it is a string and you want to parse it manually, you should use a JSON parser. Newer browsers have one built in as window.JSON, but there is open source code for parsing it as well.
var obj = JSON.parse(result);
alert('tableid is ' + obj.payload.config.tableid);

Fix JS object replacing/encoding of strings?

I have an object with a value that has spaces in it, and it gets replaced with an encoded string, like:
alldata["test"] will return "Long+name"
or something like
alldata["test"] will return "%BLong+name%B"
when it's set by using
alldata["test"] = "Long name" (or "[Long name]") via a series of code.
Am I missing something? I don't think using $.toEvalJSON is the right way to go because I haven't transformed the object into JSON. I'd rather not do a string.replace either because I'd have to capture every possible type of input that is encoded.
Thank you!
If your question is how to remove the encoding, you could always use
unescape(s)
See Escape and Unescape Functions
The issue is related to the fact that I failed to mention that the object was being assigned the string as a result of a .serialize() command. Hence a urldecode() will work perfectly.

Categories