unicode to utf-8 in JavaScript - javascript

i have output from a server like
["alex", "\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd"]
i want to convert it like
["alex", "to its right language"]
using js or jquery
i tried
function encode_utf8( s )
{
return unescape( encodeURIComponent( s ) )
}
but not working correctly
any help?
thanks in advance

I am not sure about what you mean by getting output "LIKE" the shown example...
but if you get ["alex", "\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd"] and assign it to a variable like
var foo = ["alex", "\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd"];
// alert(foo[1]) results in "��������" which actually means
// the engine has at least tried to resolve the characters
for example if you pass in correct character codes like:
var foo = ["alex", "\u003cp\u003emy UTF paragraph\u003c/p\u003e"];
// alert(foo[1]) results in "<p>my UTF paragraph</p>" which seems correct to me...
Try the examples above in a browser console (works at least for me in current Chrome)
On the other hand if you receive "\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd" every time then I assume similar to the commentors that your response already gets messed up before you are handling it in JavaScript
This article shows nicely that using Unicode characters is valid for variable naming so the same should apply to string content.

Related

I must replace some special characters on Code by Zapier

I need to replace some special characters on Zapier.
Since there are many substitutions, I want to do it through Code by Zapier.
I made the code, but I got the following error on Code by Zapier:
We had trouble sending your test through.
TypeError: str.replace is not a function
Here is the code:
str = inputData;
str.replace(/Á|Ä|À|Ã|Â/g, "A");
str.replace(/É|Ë|È|Ê/g, "E");
str.replace(/Í|Ï|Ì|Î/g, "I");
str.replace(/Ó|Ö|Ò|Õ|Ô/g, "O");
str.replace(/Ú|Ü|Ù|Û/g, "U");
output = [{outputData: str}];
I don't know why str.replace doesn't work on Code by Zapier. I tried use str = str.replace(), instead str.replace(), but it did not worked too.
Can someone help?
Looks like inputData is not a string but rather an object. So if you provided a field to the Code then you need to access it as a property of that object. Let's say the name of the variable is foo, then you need to access it as inputData.foo.replace() (see screenshot).

How to use `%value%` in javascript?

I am learning JavaScript and I see %value% in a code but I do not know what does it mean or how to use it. Can anyone please help me explain to me. Thank you very much.
var formattedLocation = HTMLworkLocation.replace("%data%", work.jobs[job].location);
"%data%" is just a literal string. This code will take the value of HTMLWorkLocation, look for the first occurrence of %data% in it, and replace that with the value of work.jobs[job].location, and store the resulting string in formattedLocation.
var work = {
jobs: [{
location: "Home office"
}]
};
var job = 0;
var HTMLworkLocation = "John is located at %data%";
var formattedLocation = HTMLworkLocation.replace("%data%", work.jobs[job].location);
console.log(formattedLocation);
This is probably part of a template system that's used to replace placeholders like %data% with values that come from a table.
You're using string.replace which takes a string or regular expression as it's first argument. Based on the code you posted it looks like you're looking for the string "%data%" (or whatever string you're looking for) in HTMLworkLocation and replacing it with the value in work.jobs[job].location. Then it is being stored in formattedLocation.
I would put a debugger; line after that line of code so you can see what the values are in the debugger console. That might help make more sense of things.
Here is more info on the str.replace method with some examples

Javascript "Replace" not working on string returned via jQuery

I'm trying to convert a currency string to a number. I'm using a replace function with a regexp that I've used successfully in a similar context before.
The currency string is captured here, in part of an "each" loop:
var unitGridPrice = jQuery(this).find(".clsPriceGridDtlPrice").html();
The result is that unitGridPrice is a currency string, something like "$2.75". I'm trying to convert it to a number here:
var priceToConvert = unitGridPrice;
var unitGridPriceNo = Number(priceToConvert.replace(/[^0-9\.]+/g, ''));
However with that last line in place, the script will not run.
If I use the value of priceToConvert it correctly displays the currency text string, so I believe the string feeding the replace function is correct.
if I change "var priceToConvert = unitGridPrice" to "var priceToConvert = "$2.75" the script properly returns 2.75. I can copy and past the value that unitGridPrice displays into the text string I'm testing with and it works, but with the variable there the script dies.
I've tried removing the regex, changing the replace to .replace('$', '') and again the script stops with the variable in place but works if I test with a fixed string.
I'm really stumped. Help??!! Thank you!!!
i had some problem while try to get number from string also, little time ago. the problem is the regex, so i changed the regex like code below.
var id = element.name.replace ( /[^\d.]/g, '' );
element.name above is like input_21,input_22, etc. and i wanna get only the number(21,22).
hope it can help you. :)

Javascript to preserve \f in returned value

I have the following javascript which works fine for the most part. It gets the user that has logged in to the site and returns their DOMAIN\username info. The problem arises when the username starts with a letter that completes a valid escape character (eg. DOMAIN\fname). The \f gets interpolated and all kinds of terrible things happen. I have tried every sort of workaround to try and replace and/or escape/encode the '\'. The problem is the \f does not seem like it is available to process/match against. The string that gets operated on is 'DOMAINname'
// DOMAIN\myusername - this works fine
// DOMAIN\fusername - fails
var userName='<%= Request.ServerVariables("LOGON_USER")%>';
userName = userName.replace('DOMAIN','');
alert("Username: " + userName);
I also see all kinds of weird behaviour if I try to do a workaround using the userName variable, I think this may be because it contains a hidden \f. I've searched high and low for a solution, can't find a thing. Tried to find out if I could remove the DOMAIN\ on the serverside but that doesn't seem available either. Does anyone have a solution or workaround? In the debugger, the initial value of the servervariable is correct but the next immediate call to that variable is wrong. So the interpolated values in the debugger look like this:
var userName='DOMAIN\fusername';
userName; // 'DOMAINusername' in debugger.
Thanks
If you're using ASP.net (as it looks like you are), use AjaxHelper.JavaScriptStringEncode or HttpUtility.JavaScriptStringEncode to output the string correctly.
var userName='<%= HttpUtility.JavaScriptStringEncode(Request.ServerVariables("LOGON_USER"))%>';

Parse ill formed JSON string

I am being sent an ill formed JSON string from a third party. I tried using JSON.parse(str) to parse it into a JavaScript object but it of course failed.
The reason being is that the keys are not strings:
{min: 100}
As opposed to valid JSON string (which parses just fine):
{"min": 100}
I need to accept the ill formed string for now. I imagine forgetting to properly quote keys is a common mistake. Is there a good way to change this to a valid JSON string so that I can parse it? For now I may have to parse character by character and try and form an object, which sounds awful.
Ideas?
You could just eval, but that would be bad security practice if you don't trust the source. Better solution would be to either modify the string manually to quote the keys or use a tool someone else has written that does this for you (check out https://github.com/daepark/JSOL written by daepark).
I did this just recently, using Uglifyjs to evaluate:
var jsp = require("uglify-js").parser;
var pro = require("uglify-js").uglify;
var orig_code = "var myobject = " + badJSONobject;
var ast = jsp.parse(orig_code); // parse code and get the initial AST
var final_code = pro.gen_code(ast); // regenerate code
$('head').append('<script>' + final_code + '; console.log(JSON.stringify(myobject));</script>');
This is really sloppy in a way, and has all the same problems as an eval() based solution, but if you just need to parse/reformat the data one time, then the above should get you a clean JSON copy of the JS object.
Depending on what else is in the JSON, you could simply do a string replace and replace '{' with '{"' and ':' with '":'.

Categories