javascript - match string against the array of regular expressions - javascript

Is there a way in JavaScript to get Boolean value for a match of the string against the array of regular expressions?
The example would be (where the 'if' statement is representing what I'm trying to achieve):
var thisExpressions = [ '/something/', '/something_else/', '/and_something_else/'];
var thisString = 'else';
if (matchInArray(thisString, thisExpressions)) {
}

Using a more functional approach, you can implement the match with a one-liner using an array function:
ECMAScript 6:
const regexList = [/apple/, /pear/];
const text = "banana pear";
const isMatch = regexList.some(rx => rx.test(text));
ECMAScript 5:
var regexList = [/apple/, /pear/];
var text = "banana pear";
var isMatch = regexList.some(function(rx) { return rx.test(text); });

http://jsfiddle.net/9nyhh/1/
var thisExpressions = [/something/, /something_else/, /and_something_else/];
var thisExpressions2 = [/else/, /something_else/, /and_something_else/];
var thisString = 'else';
function matchInArray(string, expressions) {
var len = expressions.length,
i = 0;
for (; i < len; i++) {
if (string.match(expressions[i])) {
return true;
}
}
return false;
};
setTimeout(function() {
console.log(matchInArray(thisString, thisExpressions));
console.log(matchInArray(thisString, thisExpressions2));
}, 200)​

You could use .test() which returns a boolean value when is find what your looking for in another string:
var thisExpressions = [ '/something/', '/something_else/', '/and_something_else/'];
var thisString = new RegExp('\\b' + 'else' + '\\b', 'i');
var FoundIt = thisString.test(thisExpressions);
if (FoundIt) { /* DO STUFF */ }

look this way...
function matchInArray(stringSearch, arrayExpressions){
var position = String(arrayExpressions).search(stringSearch);
var result = (position > -1) ? true : false
return result;
}

You can join all regular expressions into single one. This way the string is
scanned only once. Even with a sligthly more complex regular expression.
var thisExpressions = [ /something/, /something_else/, /and_something_else/];
var thisString = 'else';
function matchInArray(str, expr) {
var fullExpr = new RegExp(expr
.map(x=>x.source) // Just if you need to provide RegExp instances instead of strings or ...
// .map(x=>x.substring(1, x.length -2) // ...if you need to provide strings enclosed by "/" like in original question.
.join("|")
)
return str.match(fullExpr);
};
if (matchInArray(thisString, thisExpressions)) {
console.log ("Match!!");
}
In fact, even with this approach, if you need check the same expression set
against multiple strings, this is a few suboptimal because you are building
(and compiling) the same regular expression each time the function is called.
Better approach would be to use a function builder like this:
var thisExpressions = [ /something/, /something_else/, /and_something_else/];
var thisString = 'else';
function matchInArray_builder(expr) {
var fullExpr = new RegExp(expr
.map(x=>x.source) // Just if you need to provide RegExp instances instead of strings or ...
// .map(x=>x.substring(1, x.length -2) // ...if you need to provide strings enclosed by "/" like in original question.
.join("|")
)
return function (str) {
return str.match(fullExpr);
};
};
var matchInArray = matchInArray_builder(thisExpressions);
if (matchInArray(thisString)) {
console.log ("Match!!");
}

Consider breaking this problem up into two pieces:
filter out the items that match the given regular expression
determine if that filtered list has 0 matches in it
const sampleStringData = ["frog", "pig", "tiger"];
const matches = sampleStringData.filter((animal) => /any.regex.here/.test(animal));
if (matches.length === 0) {
console.log("No matches");
}

Andersh's solution will not work if you have global flags. A true return will toggle on and off on future identical tests.
regexArray.some( rx => rx.test( "a" )) // true
regexArray.some( rx => rx.test( "a" )) // false
regexArray.some( rx => rx.test( "a" )) // true
(read why here)
This works and is also a one-liner:
const isMatch = regexList.map( rx => rx.source).includes( string )
.source returns the text string of the RegExp pattern.
.map returns an array of these strings.
.includes returns if the string is in the array(if you need the index, use .indexOf)
Alternatively:
function isInsideArray( string, regexArray ){
return regexArray.map( regex => regex.source).includes( string )
}
function isInsideArray_Andersh( string, regexArray ){
return regexArray.some( rx => rx.test( string ))
}
const list_rx = [ /apple/g, /pear/g, /banana/g ],
string = "pear"
console.log( isInsideArray( string, list_rx ))
console.log( 'Andersh:', isInsideArray_Andersh( string, list_rx ))
console.log( 'Andersh (same test):', isInsideArray_Andersh( string, list_rx ))

let expressions = [ '/something/', '/something_else/', '/and_something_else/'];
let str = 'else';
here will be the check for following expressions:
if( expressions.find(expression => expression.includes(str) ) ) {
}
using Array .find() method to traverse array and .include to check substring

If you would like to use String.match(), in case your array contains both match strings and regular expressions, you can do
let str = "The quick brown fox";
let matches = ["fox", "The.*fox", /the.*fox/i];
let strInMatches = matches.some(match => str.match(match));
console.log(strInMatches);

So we make a function that takes in a literal string, and the array we want to look through. it returns a new array with the matches found. We create a new regexp object inside this function and then execute a String.search on each element element in the array. If found, it pushes the string into a new array and returns.
// literal_string: a regex search, like /thisword/ig
// target_arr: the array you want to search /thisword/ig for.
function arr_grep(literal_string, target_arr) {
var match_bin = [];
// o_regex: a new regex object.
var o_regex = new RegExp(literal_string);
for (var i = 0; i < target_arr.length; i++) {
//loop through array. regex search each element.
var test = String(target_arr[i]).search(o_regex);
if (test > -1) {
// if found push the element#index into our matchbin.
match_bin.push(target_arr[i]);
}
}
return match_bin;
}
// arr_grep(/.*this_word.*/ig, someArray)

Related

How to work out which variable has the most characters using javascript

How to work out which variable has the most characters.
For example :
var one = "qwert";
var two = "qwertyu"
var three ="qwertyuiop";
How to work out which variable has the most character.
First thing I am doing is counting the number of characters in each string.
var onelength = one.length;
var twolength = two.length;
var threelength = three.length;
The part I am struggling on is javascript to work out which of the above lengths has the most characters.
There's really no way to do this in Javascript (nor indeed in most languages).
What you're asking for is a kind of reflection. Conceptually, a function nameOfVariable that takes a variable and gives you it's string name in return:
nameOfVariable(one): 'one'
Not possible.
The answers above are attempts to work around that. Ultimately in real code this would be structured not as a bag of variables but as an object (which is kinda like a bag of variables, except you can recover the names)
const strings = {
one: 'abcde',
two: 'abcdef',
three: 'abcd',
};
// Return key in object corresponding to longest string,
// or null if object is empty.
const longest_string = strings => {
let max = null;
for (let name in strings) {
if (max === null || strings[name].length > strings[max].length) {
max = name;
}
}
return max;
}
console.log(longest_string(strings));
try
[one,two,three].reduce((a,c) => a.length>c.length? a:c,'');
var one = "qwert";
var two = "qwertyu";
var three ="qwertyuiop";
let r= [one,two,three].reduce((a,c) => a.length>c.length? a:c,'');
let v= Object.entries({one,two,three}).reduce((a,c) => a[1].length>c[1].length ? a:c,['','']);
console.log('longest variable:', v[0], '=', r);
var words=['ape','parrot','elephant'];
console.log( longestWord( words ) );
function longestWord( words ){
var longest = '';
words.forEach(function(element){
if(longest.length < element.length)
longest = element;
});
return longest;
}
You don't need to use JQuery for this. If you save the strings in an array:
const a = ["qwert","qwertadf","qwertfasdf"]
you can use this (using ES2015 features):
let max_length = Math.max(...a.map(e=>e.length))
If you want to know the greater element, you can use this:
a.findIndex(e => e.length === ml)
Just do Math.max();
Example:
Math.max(onelength, twolength, threelength);
This will return the highest value.

Filter array of strings, keeping only ones starting with vowels

I realise I've massively overengineered this, but as I'm just starting out with JS, I can't think of how to condense this into something not entirely ridiculous. I know I'm probably going to kick myself here, but can someone refactor this for me?
The aim was to create a new array from a provided one, one that only contained strings starting with vowels. It also needed to be case insensitive.
let results = []
for (let i = 0; i < strings.length; i++) {
if ((strings[i].startsWith('a')) || (strings[i].startsWith('A')) || (strings[i].startsWith('e')) || (strings[i].startsWith('E')) || (strings[i].startsWith('i')) || (strings[i].startsWith('I')) || (strings[i].startsWith('o')) || (strings[i].startsWith('O')) || (strings[i].startsWith('u')) || (strings[i].startsWith('U'))) {
results.push(strings[i])
}
}
return results
You can use a single RegExp and Array.prototype.filter() for that:
console.log([
'Foo',
'Bar',
'Abc',
'Lorem',
'Ipsum'
].filter(str => /^[aeiou]/i.test(str)));
Array.prototype.filter() returns a new array with all the elements that pass (return a truthy value) the predicate.
RegExp.prototype.test() returns true if the RegExp finds a match on the string you pass in.
Then, /^[aeiou]/i means:
^ matches the start of the string.
[aeiou] matches any of the characters inside the square brackets, a single time.
i is a case-insensitive modifier.
I'd use Array#filter and a regular expression:
let rex = /^[aeiou]/i;
let results = strings.filter(str => rex.test(str));
/^[aeiou]/i says "At the beginning of the string (^), match a, e, i, o, or u, case-insensitive (the i flag)."
Live Example:
let strings = [
"I'll match",
"But I won't",
"And I will",
"This is another one that won't",
"Useful match here"
];
let rex = /^[aeiou]/i;
let results = strings.filter(str => rex.test(str));
console.log(results);
Other answers are great, but please consider this approach shown below.
If you are new to JS, it will certainly help you understand cornerstones of JS like its array methods.
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
var new_array = arr.map(function callback(currentValue, index, array {
// Return element for new_array
}, thisArg)
Try using a REPL website like https://repl.it/ in order to see what these methods do...
The following is my proposed answer...
function onlyVowels(array) {
// For every element (word) in array we will...
return array.map((element) => {
// ...convert the word to an array with only characters...
return (element.split('').map((char) => {
// ...and map will only return those matching the regex expression
// (a || e || i || o || u)
// parameter /i makes it case insensitive
// parameter /g makes it global so it does not return after
// finding first match or "only one"
return char.match(/[aeiou]/ig)
// After getting an array with only the vowels the join function
// converts it to a string, thus returning the desired value
})).join('')
})
};
function test() {
var input = ['average', 'exceptional', 'amazing'];
var expected = ['aeae', 'eeioa', 'aai']
var actual = onlyVowels(input)
console.log(expected);
console.log(actual);
};
test()

javascript regex parsing array-syntax strings almost working

So I'm parsing strings (from a URL) that have an array-like syntax, such as:
variable[foo]
variable[foo][bar]
I need EACH of the indexes (in square brackets) to be it's own capturing group, and I need it to work with one OR MORE indexes... My regex ALMOST works, but only captures the FINAL index, not the proceeding ones, so works perfect with one index.
here you can see my best attempt, and when you hover over the second example, you'll see that group_4 becomes captured group #2 and the rest are lost. I need the captured groups to match the example names.
Just for good measure, here you can see my whole solution for parsing the regex results into actual javascript objects.
getUrlParams: function() {
let query = decodeURIComponent(window.location.search);
let paramRegex = /[&?]([\w[\]\-%]+)=([\w[\]\-%/,\s]+)(?=&|$)/igm;
let arrayRegex = /([\w]+)(?:(?:\[|%5B)([\w]+)(?:]|%5D))+/igm;
let params = {};
let match = paramRegex.exec(query);
while (match !== null) {
if (match && match[1]) {
let array = arrayRegex.exec(match[1]);
while(array !== null) {
if (array && array[1] && array[2]) {
console.log("ARRAY: ", array);
let deepParam = {};
deepParam[array[2]] = match[2];
if (array[1] in params) {
$.extend(params[array[1]], deepParam);
} else {
params[array[1]] = deepParam;
}
} else {
params[match[1]] = match[2];
}
array = arrayRegex.exec(match[1]);
}
}
match = paramRegex.exec(query);
}
return params;
},
This code works great with only one index, but once the regex captures multiple indexes, this code will have to handle it too.
Any help is much appreciated.
UPDATE:
Here is my final function solution, based on bowheart's very elegant code.
getUrlParams: function() {
let query = decodeURIComponent(window.location.search);
let paramRegex = /[&?]([\w[\]\-%]+)=([\w[\]\-%/,\s]+)(?=&|$)/igm;
let params = {};
let match = paramRegex.exec(query);
while (match !== null) {
if (match && match[1] && match[2]) {
let key = match[1];
let val = match[2];
let arrayKeys = key.split(/\[|]/g).filter(node => node);
populateObject(params, arrayKeys, val);
}
match = paramRegex.exec(query);
}
return params;
function populateObject(obj, keys, val) {
if (keys.length === 1) return obj[keys[0]] = (isNaN(+val) ? val : +val);
let nextKey = keys.shift();
if (!obj[nextKey]) obj[nextKey] = isNaN(+keys[0]) ? {} : [];
populateObject(obj[nextKey], keys, val);
}
},
What on earth gave you the idea to accomplish all this with two massive regular expressions? Just...Don't do that. You'll probably live longer. You will need regex to some degree, but always keep it as short as possible.
Here's a solution, if you're interested. You'll notice it's shorter, much easier to read, and accomplishes all the requirements:
// Recursively populates nested objects/arrays.
function populateObj(obj, keys, val) {
if (keys.length === 1) return obj[keys[0]] = val
let nextKey = keys.shift()
if (!obj[nextKey]) obj[nextKey] = isNaN(+keys[0]) ? {} : []
populateObj(obj[nextKey], keys, val)
}
let params = {}
let search = '?filters[name]=sa&filters[group_2][group_3][group_4]=4&order_bys[0][field]=name&order_bys=desc'
search.slice(1).split('&').forEach(pair => {
let [key, val] = pair.split('=')
key = key.split(/\[|]/g).filter(node => node)
populateObj(params, key, val)
})
// Just for display:
document.body.innerHTML = JSON.stringify(params, null, ' ').replace(/\n/g, '<br>')
The basic algorithm is:
Split the GET params on '&', then split each param into a key-val pair on '='.
Regex out any square brackets in the keys to get all nodes for nested arrays/objects.
Recursively traverse an object, creating child objects/arrays when necessary, and assign the given value to the last node.
Create an array if the next key is numeric. Otherwise, create an object.
(Note from your regexr snippet that order_bys[0][field]=name and order_bys=desc params are incompatible as one indicates that order_bys is a zero-indexed array and the other that it's a string. Not sure where you got that data...).
Try this regex:
(?:[\?|\&]([\w]+))|((?:\[|%5B)(\w+)(?:]|%5D))
It captures each group value as an independent match
Split on square brackets and filter out empty strings:
"variable[foo][bar]".split(/\]|\[/).filter(s => !!s)
> [ "variable", "foo", "bar" ]

evaluate formula in javascript

I have a formula and an object containing variables as a key
My object is as
{
xyz:{
v:20
},
ab:{
v:2
},
y:{
v:30
},
z:{
v:40
},
}
Now I have to evaluate the formula
Eg.
xyz+ab*(y+z)
Result : 20+2*(30+40)
Any optimized solution ?
Please note that keys are in the form of "characters..characters"
eg. ABC..XY12
Update : Actual object is
{
pnl..xyz:{
v:20
},
pxl..ab:{
v:2
},
pnl..y:{
v:30
},
pxl..z:{
v:40
},
}
and the formula is
pnl..xyz+pxl..ab*(pnl..y+pxl..z)
You can use a regex to find variable names and post that you can use eval
Sample
var data={xyz:{v:20},ab:{v:2},y:{v:30},z:{v:40},abc12:{v:12},"abc..bc":{v:31}};
function processOperation(str) {
var formula = str;
var operatios = /[+\-\*\/\(\)]/g;
var keys = formula.split(operatios);
keys.forEach(function(k) {
if (k && data[k]) formula = formula.replace(k, data[k].v)
});
console.log(formula);
return eval(formula)
}
var formula1 = "xyz+ab*(y+z)"
console.log(processOperation(formula1))
var formula2 = "xyz+ab*(y+z)-abc12"
console.log(processOperation(formula2))
var formula3 = "xyz+ab*(y+z)-12"
console.log(processOperation(formula3))
var formula4 = "xyz+ab*(y+z)-abc..bc"
console.log(processOperation(formula4))
You can write your own custom parser and evaluator, but there will be loads of edge cases, validation and operator precedence cases to be
taken care of.
I would recommend not reinventing the wheel, and using math.js , it is a lightweight dedicated library for maths in javascript.
Here is how formula evaluation can be done in a single line.
var scope = { xyz : 20, ab : 2, y : 30, z : 40 };
var answer = math.eval('xyz+ab*(y+z)', scope);
console.log('The answer is:' + answer);
<script src="http://cdnjs.cloudflare.com/ajax/libs/mathjs/3.5.3/math.min.js"></script>
This function will replace the keys of the provided obj in the provided formula string. It's curried so you can reuse the same formula with different values for the variables.
const obj = {
xyz:{ v:20 },
ab:{ v:2 },
y:{ v:30 },
z:{ v:40 }
}
const obj2 = {
'pnl..xyz':{ v:20 },
'pxl..ab':{ v:2 },
'pnl..y':{ v:30 },
'pxl..z':{ v:40 },
}
/*
* evalFormula :: String -> {key:{v:Int}} -> String
*
* replace the formula string with the obj values
*/
const evalFormula = formula => obj => {
// get the keys
const keys = Object.keys(obj)
// sort keys by length so we replace the longer strings first
keys.sort(sortBy('length'))
// reduce the keys into the formula
return keys.reduce((str, key) =>
// replace the key with it's corresponding value each iteration
str.replace(stringToRegex(key, 'g'), obj[key].v)
, formula)
}
// get a regular expression from an input string
const stringToRegex = (str, modifiers) =>
new RegExp(str.replace(/([\.\^\$\*\+\-\?\(\)\[\]\{\}\\])/g, '\$1'), modifiers)
const sortBy = prop => (a, b) => a[prop] > b[prop] ? -1 : a[prop] < b[prop] ? 1 : 0
// this is the executable function
const execFormula = evalFormula('xyz+ab*(y+z)')
const otherFormula = evalFormula('pnl..xyz+pxl..ab*(pnl..y+pxl..z)')
console.log(
execFormula(obj),
otherFormula(obj2)
)
Edit.
You would just need to add in a little escaping for the illegal characters in your keys, then create a new formula and pass in the new obj

Best javascript syntactic sugar

Here are some gems:
Literals:
var obj = {}; // Object literal, equivalent to var obj = new Object();
var arr = []; // Array literal, equivalent to var arr = new Array();
var regex = /something/; // Regular expression literal, equivalent to var regex = new RegExp('something');
Defaults:
arg = arg || 'default'; // if arg evaluates to false, use 'default', which is the same as:
arg = !!arg ? arg : 'default';
Of course we know anonymous functions, but being able to treat them as literals and execute them on the spot (as a closure) is great:
(function() { ... })(); // Creates an anonymous function and executes it
Question: What other great syntactic sugar is available in javascript?
Getting the current datetime as milliseconds:
Date.now()
For example, to time the execution of a section of code:
var start = Date.now();
// some code
alert((Date.now() - start) + " ms elapsed");
Object membership test:
var props = { a: 1, b: 2 };
("a" in props) // true
("b" in props) // true
("c" in props) // false
In Mozilla (and reportedly IE7) you can create an XML constant using:
var xml = <elem></elem>;
You can substitute variables as well:
var elem = "html";
var text = "Some text";
var xml = <{elem}>{text}</{elem}>;
Using anonymous functions and a closure to create a private variable (information hiding) and the associated get/set methods:
var getter, setter;
(function()
{
var _privateVar=123;
getter = function() { return _privateVar; };
setter = function(v) { _privateVar = v; };
})()
Being able to extend native JavaScript types via prototypal inheritance.
String.prototype.isNullOrEmpty = function(input) {
return input === null || input.length === 0;
}
Use === to compare value and type:
var i = 0;
var s = "0";
if (i == s) // true
if (i === s) // false
Multi-line strings:
var str = "This is \
all one \
string.";
Since you cannot indent the subsequent lines without also adding the whitespace into the string, people generally prefer to concatenate with the plus operator. But this does provide a nice here document capability.
Resize the Length of an Array
length property is a not read only.
You can use it to increase or decrease the size of an array.
var myArray = [1,2,3];
myArray.length // 3 elements.
myArray.length = 2; //Deletes the last element.
myArray.length = 20 // Adds 18 elements to the array; the elements have the empty value. A sparse array.
Repeating a string such as "-" a specific number of times by leveraging the join method on an empty array:
var s = new Array(repeat+1).join("-");
Results in "---" when repeat == 3.
Like the default operator, || is the guard operator, &&.
answer = obj && obj.property
as opposed to
if (obj) {
answer = obj.property;
}
else {
answer = null;
}
var tags = {
name: "Jack",
location: "USA"
};
"Name: {name}<br>From {location}".replace(/\{(.*?)\}/gim, function(all, match){
return tags[match];
});
callback for string replace is just useful.
Getters and setters:
function Foo(bar)
{
this._bar = bar;
}
Foo.prototype =
{
get bar()
{
return this._bar;
},
set bar(bar)
{
this._bar = bar.toUpperCase();
}
};
Gives us:
>>> var myFoo = new Foo("bar");
>>> myFoo.bar
"BAR"
>>> myFoo.bar = "Baz";
>>> myFoo.bar
"BAZ"
This isn't a javascript exclusive, but saves like three lines of code:
check ? value1 : value2
A little bit more on levik's example:
var foo = (condition) ? value1 : value2;
The Array#forEach on Javascript 1.6
myArray.forEach(function(element) { alert(element); });
Following obj || {default:true} syntax :
calling your function with this : hello(neededOne && neededTwo && needThree) if one parameter is undefined or false then it will call hello(false), sometimes usefull
In parsing situations with a fixed set of component parts:
var str = "John Doe";
You can assign the results directly into variables, using the "destructuring assignment" synatx:
var [fname, lname] = str.split(" ");
alert(lname + ", " + fname);
Which is a bit more readable than:
var a = str.split(" ");
alert(a[1] + ", " + a[0]);
Alternately:
var [str, fname, lname] = str.match(/(.*) (.*)/);
Note that this is a Javascript 1.7 feature. So that's Mozilla 2.0+ and Chrome 6+ browsers, at this time.
Immediately Invoked Arrow function:
var test = "hello, world!";
(() => test)(); //returns "hello, world!";
I forgot:
(function() { ... }).someMethod(); // Functions as objects
Create an anonymous object literal with simply: ({})
Example: need to know if objects have the valueOf method:
var hasValueOf = !!({}).valueOf
Bonus syntactic sugar: the double-not '!!' for converting pretty much anything into a Boolean very succinctly.
I love being able to eval() a json string and get back a fully populated data structure.
I Hate having to write everything at least twice (once for IE, again for Mozilla).
Assigining the frequently used keywords (or any methods) to the simple variables like ths
var $$ = document.getElementById;
$$('samText');
JavaScript's Date class providing a semi-"Fluent Interface". This makes up for not being able to extract the date portion from a Date class directly:
var today = new Date((new Date()).setHours(0, 0, 0, 0));
It's not a fully Fluent Interface because the following will only give us a numerical value which is not actually a Date object:
var today = new Date().setHours(0, 0, 0, 0);
Default fallback:
var foo = {}; // empty object literal
alert(foo.bar) // will alert "undefined"
alert(foo.bar || "bar"); // will alert the fallback ("bar")
A practical example:
// will result in a type error
if (foo.bar.length === 0)
// with a default fallback you are always sure that the length
// property will be available.
if ((foo.bar || "").length === 0)
Here's one I just discovered: null check before calling function:
a = b && b.length;
This is a shorter equivalent to:
a = b ? b.length : null;
The best part is that you can check a property chain:
a = b && b.c && b.c.length;
I love how simple it is to work with lists:
var numberName = ["zero", "one", "two", "three", "four"][number];
And hashes:
var numberValue = {"zero":0, "one":1, "two":2, "three":3, "four":4}[numberName];
In most other languages this would be quite heavy code. Value defaults are also lovely. For example error code reporting:
var errorDesc = {301: "Moved Permanently",
404: "Resource not found",
503: "Server down"
}[errorNo] || "An unknown error has occurred";
int to string cast
var i = 12;
var s = i+"";
element.innerHTML = ""; // Replaces body of HTML element with an empty string.
A shortcut to delete all child nodes of element.
Convert string to integer defaulting to 0 if imposible,
0 | "3" //result = 3
0 | "some string" -> //result = 0
0 | "0" -> 0 //result = 0
Can be useful in some cases, mostly when 0 is considered as bad result
Template literals
var a = 10;
var b = 20;
var text = `${a} + ${b} = ${a+b}`;
then the text variable will be like below!
10 + 20 = 30

Categories

Resources