How to use const value inside the string in JS - javascript

I'm writing React JS code for webpage.
The tutorial says the const value can be used inside the string with ${ } expression.
However, when I try it in my IDLE, it just recognize them as same string not const value.
What should I do to call saved const value inside the string
This is what it is supposed to be:
This is what I get instead:
async function getHeadlines(search) {
const url = 'https://newsapi.org/v2/top-headlines?country=au&apiKey={API_KEY}&q=${search}';
let res = await fetch(url);
let data = await res.json();
let articles = data.articles;
return articles.map((article) => ({
title: article.title,
url: article.url,
}));
}

You need to use backtick. Please go throught Template literals to understand how backtick works.
const url = `https://newsapi.org/v2/top-headlines?country=au&apiKey=${API_KEY}&q=${search}`;

As far as I can understand your question, you have to use template strings (check docs for more) for this URL:
const url = https://newsapi.org/v2/top-headlines?country=au&apiKey={API_KEY}&q=${search};
Now you can add API_KEY and search into a string.

Like everyone else said, you need to use backticks for template literals.
It looks like you are confusing non-template literal strings with template literals and their syntax (you forgot a $ in one of the literal block declarations). Let's have a little review, shall we?
Non-template literal strings look like this:
"This is a string with double quotes. It does not parse literals (${})";
'This is a string with single quotes. It does not parse literals (${})';
They use either single quotes (') or double quotes (").
Template literals are a special type of string, they allow insertion of variables and/or other data without having to use string concatenation ("This string " + "just got concatenated"). To do so, you have to wrap your code you want outputted in a ${} block, like this:
const textToInsert = "Hello, world!";
`This is a template literal. It is a string that allows easier concatenation without using the "+" operator. This parses literals, see? "${textToInsert}"`
Since the code is "executed", you can also use ternary operators:
`A random number I am thinking of is ${Math.floor(Math.random() * 10) >= 5 ? "greater than or equal to five" : "less than five"}`
Template literals are also useful if you use double quotes or single quotes in your string. If you use a single quote to declare a string that uses single quotes, you would have to escape them:
'It\'s a wonderful life'
The same applies to double quote strings using double quotes:
"\"I have no special talent. I am only passionately curious\" - Albert Einstein"
But, if you use template literals, you can use both single and double quotes without escaping them (note that you will have to escape backticks (`)):
`
It's a wonderful life.
"I have no special talent. I am only passionately curious" - Albert Einstein
`
Oh, I forgot to mention - template literals support newlines!!!
The conclusion? Template literals are powerful! You just have to know how to use them :)
So, what would your fixed template literal look like?
It would look like this:
`https://newsapi.org/v2/top-headlines?country=au&apiKey=${API_KEY}&q=${search}`;

Related

Regex substitution '$1' - why is it a string?

Silly question, but I'll ask it anyway: Why is the substitution part of a regular expression in JavaScript encompassed in quotes as a string, where it seems to be a variable in its own right? eg '$2'
alert("banana split") // nana split
function reg(afilename)
{
var rexp = new RegExp(/^(ba)(.+)/gim)
var newName = afilename.replace(rexp, '$2')
return newName
}
Because it's not a [Javascript] variable in its own right.
If you didn't single-quote it, JavaScript would try to pass the value of the variable $2 as an argument (yes, you can give JavaScript variables names starting with $), except you don't have one.
This way, the Regex engine gets the actual, literal string $2, and gives it its own special meaning.
It's a perfect example of abstraction, where you can witness two "layers" of software interacting. Consider also document.write('<p>Text</p>'); — you wouldn't want JavaScript to try to parse that HTML, right? You want to pass it verbatim to the entity that is going to handle it.

es6 multiline template strings with no new lines and allow indents

Been using es6 more and more for most work these days. One caveat is template strings.
I like to limit my line character count to 80. So if I need to concatenate a long string, it works fine because concatenation can be multiple lines like this:
const insert = 'dog';
const str = 'a really long ' + insert + ' can be a great asset for ' +
insert + ' when it is a ' + dog;
However, trying to do that with template literals would just give you a multi-line string with ${insert} placing dog in the resulting string. Not ideal when you want to use template literals for things like url assembly, etc.
I haven't yet found a good way to maintain my line character limit and still use long template literals. Anyone have some ideas?
The other question that is marked as an accepted is only a partial answer. Below is another problem with template literals that I forgot to include before.
The problem with using new line characters is that it doesn't allow for indentation without inserting spaces into the final string. i.e.
const insert = 'dog';
const str = `a really long ${insert} can be a great asset for\
${insert} when it is a ${insert}`;
The resulting string looks like this:
a really long dog can be a great asset for dog when it is a dog
Overall this is a minor issue but would be interesting if there was a fix to allow multiline indenting.
Two answers for this problem, but only one may be considered optimal.
Inside template literals, javascript can be used inside of expressions like ${}. Its therefore possible to have indented multiline template literals such as the following. The caveat is some valid js character or value must be present in the expression, such as an empty string or variable.
const templateLiteral = `abcdefgh${''
}ijklmnopqrst${''
}uvwxyz`;
// "abcdefghijklmnopqrstuvwxyz"
This method makes your code look like crap. Not recommended.
The second method was recommended by #SzybkiSasza and seems to be the best option available. For some reason concatenating template literals didn't occur to me as possible. I'm derp.
const templateLiteral = `abcdefgh` +
`ijklmnopqrst` +
`uvwxyz`;
// "abcdefghijklmnopqrstuvwxyz"
Why not use a tagged template literal function?
function noWhiteSpace(strings, ...placeholders) {
let withSpace = strings.reduce((result, string, i) => (result + placeholders[i - 1] + string));
let withoutSpace = withSpace.replace(/$\n^\s*/gm, ' ');
return withoutSpace;
}
Then you can just tag any template literal you want to have line breaks in:
let myString = noWhiteSpace`This is a really long string, that needs to wrap over
several lines. With a normal template literal you can't do that, but you can
use a template literal tag to allow line breaks and indents.`;
The provided function will strip all line breaks and line-leading tabs & spaces, yielding the following:
> This is a really long string, that needs to wrap over several lines. With a normal template literal you can't do that, but you can use a template literal tag to allow line breaks and indents.
I published this as the compress-tag library.

Do the single quote (') and double quote (") work in jQuery like they do in PHP?

Does either the single quote (') or double quote (") have a function where they will parse through the string and replace variables with values? I remember that in PHP the parsing engine will parse through the string and automatically switch out any variables with their values (I don't remember which actually has that effect off the top of my head) so you don't have to type "somestring" + aVariableusing the concatenation
operator. in what I have read through so far on http://www.tutorialspoint.com/jquery/jquery-basics.htm I haven't been able to find anything about it. Also unless I missed it the post When to use double or single quotes in JavaScript? does not directly cover this information.
Single quotes and double quotes are identical in JavaScript and do not interpolate variables. In my experience it's good practise to stick with single quotes in JS, allowing you to use double quotes inside those strings (without escaping) for things like HTML attributes.
However, ES2015 introduced "template strings" using backticks, which are somewhat like PHP's strings in that they can interpolate into a string, and are if anything more powerful because they'll actually interpolate any expression, not just plain variables:
let bar = 'bar';
let foo = `${bar}`;
let FOO = `${bar.toUpperCase()}`;
No, there is no such thing as variable interpolation in JavaScript (and therefore jQuery)
And that's a very good thing! While PHP has all variables identified by $ at the start, JavaScript does not. So even a simple string such as "Hello world!" could go horribly wrong if you had a variable called world...
You may be interested in a templating system, of which there are many options out there - a quick Google search will turn up results, but here's a list of some with examples and stuff.

Parsing malformed JSON in JavaScript

Thanks for looking!
BACKGROUND
I am writing some front-end code that consumes a JSON service which is returning malformed JSON. Specifically, the keys are not surrounded with quotes:
{foo: "bar"}
I have NO CONTROL over the service, so I am correcting this like so:
var scrubbedJson = dirtyJson.replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:/g, '"$2": ');
This gives me well formed JSON:
{"foo": "bar"}
Problem
However, when I call JSON.parse(scrubbedJson), I still get an error. I suspect it may be because the entire JSON string is surrounded in double quotes but I am not sure.
UPDATE
This has been solved--the above code works fine. I had a rogue single quote in the body of the JSON that was returned. I got that out of there and everything now parses. Thanks.
Any help would be appreciated.
You can avoid using a regexp altogether and still output a JavaScript object from a malformed JSON string (keys without quotes, single quotes, etc), using this simple trick:
var jsonify = (function(div){
return function(json){
div.setAttribute('onclick', 'this.__json__ = ' + json);
div.click();
return div.__json__;
}
})(document.createElement('div'));
// Let's say you had a string like '{ one: 1 }' (malformed, a key without quotes)
// jsonify('{ one: 1 }') will output a good ol' JS object ;)
Here's a demo: http://codepen.io/csuwldcat/pen/dfzsu (open your console)
something like this may help to repair the json ..
$str='{foo:"bar"}';
echo preg_replace('/({)([a-zA-Z0-9]+)(:)/','$1"$2"${3}',$str);
Output:
{"foo":"bar"}
EDIT:
var str='{foo:"bar"}';
str.replace(/({)([a-zA-Z0-9]+)(:)/,'$1"$2"$3')
There is a project that takes care of all kinds of invalid cases in JSON https://github.com/freethenation/durable-json-lint
I was trying to solve the same problem using a regEx in Javascript. I have an app written for Node.js to parse incoming JSON, but wanted a "relaxed" version of the parser (see following comments), since it is inconvenient to put quotes around every key (name). Here is my solution:
var objKeysRegex = /({|,)(?:\s*)(?:')?([A-Za-z_$\.][A-Za-z0-9_ \-\.$]*)(?:')?(?:\s*):/g;// look for object names
var newQuotedKeysString = originalString.replace(objKeysRegex, "$1\"$2\":");// all object names should be double quoted
var newObject = JSON.parse(newQuotedKeysString);
Here's a breakdown of the regEx:
({|,) looks for the beginning of the object, a { for flat objects or , for embedded objects.
(?:\s*) finds but does not remember white space
(?:')? finds but does not remember a single quote (to be replaced by a double quote later). There will be either zero or one of these.
([A-Za-z_$\.][A-Za-z0-9_ \-\.$]*) is the name (or key). Starts with any letter, underscore, $, or dot, followed by zero or more alpha-numeric characters or underscores or dashes or dots or $.
the last character : is what delimits the name of the object from the value.
Now we can use replace() with some dressing to get our newly quoted keys:
originalString.replace(objKeysRegex, "$1\"$2\":")
where the $1 is either { or , depending on whether the object was embedded in another object. \" adds a double quote. $2 is the name. \" another double quote. and finally : finishes it off.
Test it out with
{keyOne: "value1", $keyTwo: "value 2", key-3:{key4:18.34}}
output:
{"keyOne": "value1","$keyTwo": "value 2","key-3":{"key4":18.34}}
Some comments:
I have not tested this method for speed, but from what I gather by reading some of these entries is that using a regex is faster than eval()
For my application, I'm limiting the characters that names are allowed to have with ([A-Za-z_$\.][A-Za-z0-9_ \-\.$]*) for my 'relaxed' version JSON parser. If you wanted to allow more characters in names (you can do that and still be valid), you could instead use ([^'":]+) to mean anything other than double or single quotes or a colon. You can have all sorts of stuff in here with this expression, so be careful.
One shortcoming is that this method actually changes the original incoming data (but I think that's what you wanted?). You could program around that to mitigate this issue - depends on your needs and resources available.
Hope this helps.
-John L.
How about?
function fixJson(json) {
var tempString, tempJson, output;
tempString = JSON.stringify(json);
tempJson = JSON.parse(tempString);
output = JSON.stringify(tempJson);
return output;
}

How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?

Say I have a string variable (var str) as follows-
Dude, he totally said that "You Rock!"
Now If I'm to make it look like as follows-
Dude, he totally said that "You Rock!"
How do I accomplish this using the JavaScript replace() function?
str.replace("\"","\\""); is not working so well. It gives unterminated string literal error.
Now, if the above sentence were to be stored in a SQL database, say in MySQL as a LONGTEXT (or any other VARCHAR-ish) datatype, what else string optimizations I need to perform?
Quotes and commas are not very friendly with query strings. I'd appreciate a few suggestions on that matter as well.
You need to use a global regular expression for this. Try it this way:
str.replace(/"/g, '\\"');
Check out regex syntax and options for the replace function in Using Regular Expressions with JavaScript.
Try this:
str.replace("\"", "\\\""); // (Escape backslashes and embedded double-quotes)
Or, use single-quotes to quote your search and replace strings:
str.replace('"', '\\"'); // (Still need to escape the backslash)
As pointed out by helmus, if the first parameter passed to .replace() is a string it will only replace the first occurrence. To replace globally, you have to pass a regex with the g (global) flag:
str.replace(/"/g, "\\\"");
// or
str.replace(/"/g, '\\"');
But why are you even doing this in JavaScript? It's OK to use these escape characters if you have a string literal like:
var str = "Dude, he totally said that \"You Rock!\"";
But this is necessary only in a string literal. That is, if your JavaScript variable is set to a value that a user typed in a form field you don't need to this escaping.
Regarding your question about storing such a string in an SQL database, again you only need to escape the characters if you're embedding a string literal in your SQL statement - and remember that the escape characters that apply in SQL aren't (usually) the same as for JavaScript. You'd do any SQL-related escaping server-side.
The other answers will work for most strings, but you can end up unescaping an already escaped double quote, which is probably not what you want.
To work correctly, you are going to need to escape all backslashes and then escape all double quotes, like this:
var test_str = '"first \\" middle \\" last "';
var result = test_str.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');
depending on how you need to use the string, and the other escaped charaters involved, this may still have some issues, but I think it will probably work in most cases.
var str = 'Dude, he totally said that "You Rock!"';
var var1 = str.replace(/\"/g,"\\\"");
alert(var1);

Categories

Resources