I'm using the Google Maps API. Please see this JSON response.
The HTML instructions is written like this:
"html_instructions" : "Turn \u003cb\u003eleft\u003c/b\u003e onto \u003cb\u003eEnggårdsgade\u003c/b\u003e"
How can I convert the unicodes \u003c, \u003e etc. in JavaScript?
Those are Unicode character escape sequences in a JavaScript string. As far as JavaScript is concerned, they are the same character.
'\u003cb\u003eleft\u003c/b\u003e' == '<b>left</b>'; // true
So, you don’t need to do any conversion at all.
Below is a simpler way thanks to modern JS .
ES6 / ES2015 introduced the normalize() method on the String prototype, so we can do:
var directions = "Turn \u003cb\u003eleft\u003c/b\u003e onto \u003cb\u003eEnggårdsgade\u003c/b\u003e";
directions.normalize();
//it will return : "Turn <b>left</b> onto <b>Enggårdsgade</b>"
Refer to this article : https://flaviocopes.com/javascript-unicode/
you can use JSON.parse directly on JSON response then the unicode characters will automatically converted to its html counter parts (\u003c will be converted to < sign in html)
JSON.parse(JSON.stringify({a : 'Turn \u003cb\u003eleft\u003c/b\u003e onto \u003cb\u003eEnggårdsgade\u003c/b\u003e'}));
This small function may help
String.prototype.toUnicode = function(){
var hex, i;
var result = "";
for (i=0; i<this.length; i++) {
hex = this.charCodeAt(i).toString(16);
result += ("\\u00"+hex).slice(-7);
}
return result;
};
Related
I'm utilizing the google maps API, and I have some coordinates I've gotten in LongLat that I need to convert to LatLong
Here's the string:
1.5887868,50.8315241|1.5830702,50.8466931|1.590201,50.827209|1.5887868,50.8315241
where 1.5887868 is the first longitudinal coordinate, 50.8315241 is the first latitudinal cooridnate, and the pairs are broken up by |
It's my belief that I need to change the order of these paired items because google can only accept LatLnghere, (LngLat causes an error)
center:new google.maps.LngLat(50.8315241, 1.5887868),
What's the easiest way to go about this? Or - is there a way for me to use my coorinates in long,lat format?
This should do what you're looking for:
var longLatStr = "1.5887868,50.8315241|1.5830702,50.8466931|1.590201,50.827209|1.5887868,50.8315241";
var latLongStr = longLatStr.split("|").map(function(longLatPair){
var longLatPairArr = longLatPair.split(",");
return longLatPairArr[1] + "," + longLatPairArr[0];
}).join('|');
You can swap anything in a string with the .replace() function (relies on regex). For whatever you want swapped, match both by capturing each thing to be swapped in parentheses, then use $n in the replacement string to specify where you want it moved to. See this example:
var c = '1.5887868,50.8315241|1.5830702,50.8466931|1.590201,50.827209|1.5887868,50.8315241';
var swapped = c.replace(/(-?\d+\.\d+),(-?\d+\.\d+)/g, '$2,$1');
You can read the full documentation on using special replacement patterns on MDN.
I am trying get the string in the following URL to display on my webpage.
http://example.com?ks4day=Friday+September+13th
EDIT: The date in the URL will change from person to person as it's merged in by my CRM program.
I can get it to display on my webpage using the code below, the problem is the plus signs (+) come through as well.
eg. Friday+September+13th
What I need it to do is replace the plus signs (+) with spaces so it looks like this:
eg. Friday September 13th
I'm new to this so I'm having some trouble working it out.
Any help would be appreciated.
This is the code i'm using in a .js file
function qs(search_for) {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0 && search_for == parms[i].substring(0,pos)) {
return parms[i].substring(pos+1);;
}
}
return "";
}
This is the code i'm using on my webpage to make it display
<script type="text/javascript">document.write(qs("ks4day"));</script>
Although Bibhu's answer will work for this one case, you'll need to add decodeURIComponent if you have encoded characters in your URI string. You also want to make sure you do the replace before the decode in case you have a legitimate + in your URI string (as %2B).
I believe this is the best general way to do it:
var x = qs("ks4day"); // 'Friday+September+13th'
x = x.replace(/\+/g, '%20'); // 'Friday%20September%2013th'
x = decodeURIComponent(x); // 'Friday September 13th'
Here's an example of when it might be useful:
var x = '1+%2B+1+%3D+2';
x = x.replace(/\+/g, '%20'); // '1%20%2B%201%20%3D%202'
x = decodeURIComponent(x); // '1 + 1 = 2'
You can use replace() for this purpose
var dateString = 'Friday+September+13th';
var s = dateString .replace(/\+/g, ' ');
Parsing strings using regex is often prone to so many errors. Thankfully all modern browsers provide URLSearchParams to handle params from url strings in a proper way:
var params = new URLSearchParams(window.location.search);
var value = params.get('ks4day');
// "Friday September 13th"
Ps: There is also a good polyfill for old browsers.
Have you tried https://www.npmjs.com/package/querystring ?
import { parse } from 'querystring';
parse('ks4day=Friday+September+13th')
returns
{ 'ks4day': 'Friday September 13th' }
Assuming you are using something like Webpack that knows how to process import statements
If that's what you are doing, the plus sign will not be the only one that is going to give you a hard time. The apostrophe ('), equals (=), plus (+) and basically anything not in the permitted URL characters (see Percent-encoding # Wikipedia) is going to get escaped.
You are most likely looking for the decodeURIComponent function.
I would like to build my own translation function in javascript.
I already have a function language.lookup(key) which translates a word or expression:
var frenchHello = language.lookup('hello') //'bonjour'
Now I would like to write a function which takes a html string and translates it with my lookup function. In the html string I will have a special syntax for example #[translationkey] that will point out that this word should be translated.
This is the result I want:
var html = '<div><span>#[hello]</span><span>#[sir]</span>'
language.translate(html) //'<div><span>bonjour</span><span>monsieur</span>
How would I write language.translate?
My idea is to filter out my special syntax with regex and then run language.lookup on each key. Maybe with string replace or something.
I suck when it comes to regex and I've only come up with a very incomplete example but I include it anyway so maybe someone get the idea of what I am trying to do. Then if there is a better but complete different solution that is more than welcome.
var value = "#[hello], nice to see you.";
lookup = function(word){
return "bonjour";
};
var res = new RegExp( "\\b(hello)\\b", "gi" ).exec(value)
for (var c1 = 0; c1 < res.length; c1++){
value = value.replace(res[c1], lookup(res[c1]))
}
alert(value) //#[bonjour], nice to see you.
The regex should of course not filter out the word hello but the syntax and then collect the key by grouping or similar.
Can anyone help?
Just use String.replace method's ability to call function specified as second argument to generate replacement text and make a global replace using regexp matching your syntax:
var value = "#[hello], #[sir], nice to see you.";
lookup = function(full_match, word){
if(word == 'hello')
return "bonjour";
if(word == 'sir')
return "monsieur"
};
console.log(value.replace(/#\[(.+?)\]/gi, lookup))
Result:
bonjour, monsieur, nice to see you.
Of course when your replacement list gets bigger, you'd better use lookup object instead of series of ifs in lookup function, but you can really do whatever you want there.
You can try this to find all occurrences:
var re = new RegExp('#\\[([^\\]]+?)\\]', 'gi'),
str = '#[value1] plain text #[value2]',
match;
while (match = re.exec(str)) {
console.log(match);
}
You could use something like:
#\\[[^\\]]*\\]
Which matches the hash followed by an opening square bracket followed by zero or more characters NOT including the closing square bracket, followed by a closed square bracket.
Alternatively, perhaps it would be better to handle the translation at the server side (maybe even through your template engine) and send back to your client the translated response. Otherwise, (depending on the specific problem you are dealing with of course), you might end up sending a lot of data to the browser which might make your application respond slowly.
EDIT:
Here is a working piece of code:
var q="This #[ANIMAL1] was eaten by that #[ANIMAL2]";
var u = {"#[ANIMAL1]":"Lion","#[ANIMAL2]":"Frog"};
function insertAnimal(aString, lookup){
var res = (new RegExp("#\\[[^\\]]*\\]", "gi"))
while (m = res.exec(aString)){
aString = aString.replace(m, lookup[m])
}
return aString;
}
function main(){
alert(insertAnimal(q,u));
}
You can call the "main()" from an HTML document's body onload event
I can compare your requirement to 'resolving template texts within content'. If it is feasible to use Jquery , you should try Handlebars.js
.
Does there exist a provision for obtaining the corresponding names?
A function I'm writing has to both set the style via element.style[propnameCamelCase] and retrieve the existing rendered value via document.defaultView.getComputedStyle(element,'').getPropertyValue(propname-regular), and I can hardly justify having to pass two separate but semantically identical arguments to this function.
I know that for most of them it's a fairly straightforward transcription between camelCase and hyphen-delimited with the same words, so I can use regexes to convert them. But maybe there are a few that are not like this?
Off the top of my head I'm having a hard time figuring out how to deal with the capitalized letters for camel case with regular expressions.
edit: Ah, I could use a function for regex replace, each time I see a hyphen, convert next letter to upper case.
So you're basically reinventing jQuery.css(). Maybe a look at how jQuery solved the camelCase problem might help: https://github.com/jquery/jquery/blob/master/src/core.js#L600
I was about to ask question about the same thing (and I intended to name it "Translate css names to\from javascript counterparts"). Somehow I ended up writing my own solution.
function cssNameToJsName(name)
{
var split = name.split("-");
var output = "";
for(var i = 0; i < split.length; i++)
{
if (i > 0 && split[i].length > 0 && !(i == 1 && split[i] == "ms"))
{
split[i] = split[i].substr(0, 1).toUpperCase() + split[i].substr(1);
}
output += split[i];
}
return output;
}
function jsNameToCssName(name)
{
return name.replace(/([A-Z])/g, "-$1").toLowerCase();
}
I'd like to mention that CSSStyleDeclaration.style.setProperty accepts css/hyphen type property names without conversion, as documented here
Try this hyphenated property, for example:
document.body.style.setProperty("background-color", "red");
You can also do this:
document.body.style["background-color"] = "silver";
These approaches - if you can use them - may be simpler.
It appears that JavaScript auto-converts certain special characters into HTML entities when outputting content via the innerHTML() function. This is a problem, since I need to be able to output < and > without converting to gt; and lt;
Can this auto-conversion be prevented, reversed, or escaped? So far, no matter what I do, < and > are always automatically encoded into HTML entities.
Example code:
function DisplayQueries() {
var IDs = ['AllOpenedINC','AllOpenedCRQ','AllClosedINC','AllClosedCRQ','SameDayINC','SameDayCRQ','NotSameDayINC','NotSameDayCRQ',
'StillOpenINC','StillOpenCRQ','OpenOldINC','OpenOldCRQ','OtherQueuesINC','OtherQueuesCRQ']
for (var i = 0; i < IDs.length; i++) {
if (eval(IDs[i]))
document.getElementById(IDs[i]).innerHTML = eval(IDs[i]);
}
}
Example query variable:
AllOpenedINC = "('Company*+' = \"test\" OR 'Summary*' = \"%test%\") AND ('Submit Date' >= \"" + theDate +
" 12:00:00 AM\" AND 'Submit Date' <= \"" + theDate + " 11:59:59 PM\")" + nameINC;
You should focus on what you want to accomplish as a result, rather than the way of doing it. innerHTML() does encode, innerText() and textContent() do encoding too. So you should decode your strings if you want them as < or > back.
You can use this unescapeHTML() function to get your results as you want them.
function unescapeHTML() {
return this.stripTags().replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');
}
I hope this helps. I've copied it from Prototype.
I think your question is based on a false premise. Just make a very simple test:
document.getElementById("testdiv").innerHTML = '<h1><em>Hello</em></h1>';
if this works fine then the problem is not on the JS side, instead you use some other components in your system which HTML-encode your characters.
I figured out what's going on. There's no easy way to prevent innerHTML from converting special characters to HTML entities, but since the problem was surfacing when copying the content of a DIV to the clipboard (using IE-only JS, which works since this is in a government environment where everyone has to use IE), I just used the replace() function to re-convert the HTML entities back to < and >.
You can use jquery and .append()