I'm struggling to figure out how to get this regex to work without needing a loop. Here's the code that works:
var template = {name: "Oscar", anotherName: "your twin", hello: 'world'}
var str = "Hello, {{name}} I'm {{anotherName}}. Hello to the {{hello}}"
Object.keys(template).forEach(function (keyName) {
pattern = new RegExp('{{' + keyName + '}}', 'g');
str = str.replace(pattern, template[keyName]);
})
// => str "Hello, Oscar I'm your twin. Hello to the world"
The thing about this code I don't like is that it's in a loop generating regex when I feel like a regex should be able to handle this use case. However, my regex is always only matching the last item. I was doing regex like str.match(/({{.}})/gi) but then only the {{hello}} was getting matched.
Preferably I'd like to do something where I can get all matches in an array and then map the array like matchesFromRegex.map(match => template[match]).join('')
Also, I'm in an vanilla JS environment so .matchAll (which isn't supported in IE) wouldn't work.
In a RegExp string, { has a special meaning (it lets you set a cardinality for a match, like \d{5} for five digits).
Use new RegExp('\\{\\{' + keyName + '}}', 'g'); instead. The double backslash in JavaScript will create a backslash, which will escape the { character.
If you want to avoid the loop, you can use the function-based version of replace instead:
const pattern = /\{\{([^}]*)}}/g;
str.replace(pattern, (_, key) => template[key]);
To break it down, pattern has a capture group (the parts in ()). The String.prototype.replace function can let you supply a function for doing replacements, which will be passed your match results.
I have to setup a config file by code and pass in some variables
const confEntry = String.raw`
[${internal}]
...
user = bg${internal}
auth_user = bg${internal}
...
secret = ${password}
...
from_sip_src_setting=from_display,sip_from_user_setting=${account_username}
...
`;
when it comes to
from_sip_src_setting=from_display,sip_from_user_setting=${account_username}
I don't want to pass in a variable. =${account_username} should be written as plain text. Obviously I get the error
account_username is not defined
How can I ignore this and write plain text for this specific part?
If you want to keep ${} in your final string, you can escape either the dollar sign, the curly braces or both using a backslash \, this will break the ${} pattern and it will be treated as regular text:
const world = 'world';
console.log(`\${hello} $\{world\} \$\{hello\} ${world}`);
However, since String.raw escapes everything, you cannot use that trick.
But, using the above trick, you could generate the ${str} string using an inner template string like this:
const world = 'world';
const raw = x => `\${${x}}`;
console.log(String.raw`${raw('hello')} ${world}`);
Or simply:
const world = 'world';
const raw = x => '${' + x + '}';
console.log(String.raw`${raw('hello')} ${world}`);
You will need to escape the curly braces in order for it not to be interpreted as a string literal
So instead of ${account_username} ist would be $\{account_username\}
String.raw used to get the raw string form of template
strings, that is, substitutions (e.g. ${foo}) are processed, but
escapes (e.g. \n) are not.
String.raw do not process your escapes.
let a = String.raw`hello\nhow are you`
let b = `hello\nhow are you`
console.log(a) //raw string output
console.log(b) // template string output
In JavaScript, a backtick† seems to work the same as a single quote. For instance, I can use a backtick to define a string like this:
var s = `abc`;
Is there a way in which the behavior of the backtick actually differs from that of a single quote?
† Note that among programmers, "backtick" is one name for what is more generally called the grave accent. Programmers also sometimes use the alternate names "backquote" and "backgrave". Also, on Stack Overflow and elsewhere, other common spellings for "backtick" are "back-tick" and "back tick".
This is a feature called template literals.
They were called "template strings" in prior editions of the ECMAScript 2015 specification.
Template literals are supported by Firefox 34, Chrome 41, and Edge 12 and above, but not by Internet Explorer.
Examples: http://tc39wiki.calculist.org/es6/template-strings/
Official specification: ECMAScript 2015 Language Specification, 12.2.9 Template Literal Lexical Components (a bit dry)
Template literals can be used to represent multi-line strings and may use "interpolation" to insert variables:
var a = 123, str = `---
a is: ${a}
---`;
console.log(str);
Output:
---
a is: 123
---
What is more important, they can contain not just a variable name, but any JavaScript expression:
var a = 3, b = 3.1415;
console.log(`PI is nearly ${Math.max(a, b)}`);
ECMAScript 6 comes up with a new type of string literal, using the backtick as the delimiter. These literals do allow basic string interpolation expressions to be embedded, which are then automatically parsed and evaluated.
let person = {name: 'RajiniKanth', age: 68, greeting: 'Thalaivaaaa!' };
let usualHtmlStr = "<p>My name is " + person.name + ",</p>\n" +
"<p>I am " + person.age + " old</p>\n" +
"<strong>\"" + person.greeting + "\" is what I usually say</strong>";
let newHtmlStr =
`<p>My name is ${person.name},</p>
<p>I am ${person.age} old</p>
<p>"${person.greeting}" is what I usually say</strong>`;
console.log(usualHtmlStr);
console.log(newHtmlStr);
As you can see, we used the ` around a series of characters, which are interpreted as a string literal, but any expressions of the form ${..} are parsed and evaluated inline immediately.
One really nice benefit of interpolated string literals is they are allowed to split across multiple lines:
var Actor = {"name": "RajiniKanth"};
var text =
`Now is the time for all good men like ${Actor.name}
to come to the aid of their
country!`;
console.log(text);
// Now is the time for all good men like RajiniKanth
// to come to the aid of their
// country!
Interpolated Expressions
Any valid expression is allowed to appear inside ${..} in an interpolated string literal, including function calls, inline function expression calls, and even other interpolated string literals!
function upper(s) {
return s.toUpperCase();
}
var who = "reader"
var text =
`A very ${upper("warm")} welcome
to all of you ${upper(`${who}s`)}!`;
console.log(text);
// A very WARM welcome
// to all of you READERS!
Here, the inner `${who}s` interpolated string literal was a little bit nicer convenience for us when combining the who variables with the "s" string, as opposed to who + "s". Also note that an interpolated string literal is just lexically scoped where it appears, not dynamically scoped in any way:
(e.g. below: a name variable gets interpolated with the value held in the scope where the template-literal is defined; assigning another value in the foo function's scope will have no effect)
function foo(str) {
var name = "foo";
console.log(str);
}
function bar() {
var name = "bar";
foo(`Hello from ${name}!`);
}
var name = "global";
bar(); // "Hello from bar!"
Using the template literal for the HTML is definitely more readable by reducing the annoyance.
The plain old way:
'<div class="' + className + '">' +
'<p>' + content + '</p>' +
'Let\'s go'
'</div>';
With ECMAScript 6:
`<div class="${className}">
<p>${content}</p>
Let's go
</div>`
Your string can span multiple lines.
You don't have to escape quotation characters.
You can avoid groupings like: '">'
You don't have to use the plus operator.
Tagged Template Literals
We can also tag a template string, when a template string is tagged, the literals and substitutions are passed to function which returns the resulting value.
function myTaggedLiteral(strings) {
console.log(strings);
}
myTaggedLiteral`test`; //["test"]
function myTaggedLiteral(strings, value, value2) {
console.log(strings, value, value2);
}
let someText = 'Neat';
myTaggedLiteral`test ${someText} ${2 + 3}`;
//["test", ""]
// "Neat"
// 5
We can use the spread operator here to pass multiple values. The first argument—we called it strings—is an array of all the plain strings (the stuff between any interpolated expressions).
We then gather up all subsequent arguments into an array called values using the ... gather/rest operator, though you could of course have left them as individual named parameters following the strings parameter like we did above (value1, value2, etc.).
function myTaggedLiteral(strings, ...values) {
console.log(strings);
console.log(values);
}
let someText = 'Neat';
myTaggedLiteral`test ${someText} ${2 + 3}`;
//["test", ""]
// "Neat"
// 5
The argument(s) gathered into our values array are the results of the already evaluated interpolation expressions found in the string literal. A tagged string literal is like a processing step after the interpolations are evaluated, but before the final string value is compiled, allowing you more control over generating the string from the literal. Let's look at an example of creating reusable templates.
const Actor = {
name: "RajiniKanth",
store: "Landmark"
}
const ActorTemplate = templater`<article>
<h3>${'name'} is a Actor</h3>
<p>You can find his movies at ${'store'}.</p>
</article>`;
function templater(strings, ...keys) {
return function(data) {
let temp = strings.slice();
keys.forEach((key, i) => {
temp[i] = temp[i] + data[key];
});
return temp.join('');
}
};
const myTemplate = ActorTemplate(Actor);
console.log(myTemplate);
Raw Strings
Our tag functions receive a first argument we called strings, which is an array. But there’s an additional bit of data included: the raw unprocessed versions of all the strings. You can access those raw string values using the .raw property, like this:
function showraw(strings, ...values) {
console.log(strings);
console.log(strings.raw);
}
showraw`Hello\nWorld`;
As you can see, the raw version of the string preserves the escaped \n sequence, while the processed version of the string treats it like an unescaped real new-line. ECMAScript 6 comes with a built-in function that can be used as a string literal tag: String.raw(..). It simply passes through the raw versions of the strings:
console.log(`Hello\nWorld`);
/* "Hello
World" */
console.log(String.raw`Hello\nWorld`);
// "Hello\nWorld"
Backticks (`) are used to define template literals. Template literals are a new feature in ECMAScript 6 to make working with strings easier.
Features:
we can interpolate any kind of expression in the template literals.
They can be multi-line.
Note: we can easily use single quotes (') and double quotes (") inside the backticks (`).
Example:
var nameStr = `I'm "Alpha" Beta`;
To interpolate the variables or expression we can use the ${expression} notation for that.
var name = 'Alpha Beta';
var text = `My name is ${name}`;
console.log(text); // My name is Alpha Beta
Multi-line strings means that you no longer have to use \n for new lines anymore.
Example:
const name = 'Alpha';
console.log(`Hello ${name}!
How are you?`);
Output:
Hello Alpha!
How are you?
Apart from string interpolation, you can also call a function using back-tick.
var sayHello = function () {
console.log('Hello', arguments);
}
// To call this function using ``
sayHello`some args`; // Check console for the output
// Or
sayHello`
some args
`;
Check styled component. They use it heavily.
Backticks enclose template literals, previously known as template strings. Template literals are string literals that allow embedded expressions and string interpolation features.
Template literals have expressions embedded in placeholders, denoted by the dollar sign and curly brackets around an expression, i.e. ${expression}. The placeholder / expressions get passed to a function. The default function just concatenates the string.
To escape a backtick, put a backslash before it:
`\`` === '`'; => true
Use backticks to more easily write multi-line string:
console.log(`string text line 1
string text line 2`);
or
console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);
vs. vanilla JavaScript:
console.log('string text line 1\n' +
'string text line 2');
or
console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');
Escape sequences:
Unicode escapes started by \u, for example \u00A9
Unicode code point escapes indicated by \u{}, for example \u{2F804}
Hexadecimal escapes started by \x, for example \xA9
Octal literal escapes started by \ and (a) digit(s), for example \251
Summary:
Backticks in JavaScript is a feature which is introduced in ECMAScript 6 // ECMAScript 2015 for making easy dynamic strings. This ECMAScript 6 feature is also named template string literal. It offers the following advantages when compared to normal strings:
In Template strings linebreaks are allowed and thus can be multiline. Normal string literals (declared with '' or "") are not allowed to have linebreaks.
We can easily interpolate variable values to the string with the ${myVariable} syntax.
Example:
const name = 'Willem';
const age = 26;
const story = `
My name is: ${name}
And I'm: ${age} years old
`;
console.log(story);
Browser compatibility:
Template string literal are natively supported by all major browser vendors (except Internet Explorer). So it is pretty safe to use in your production code. A more detailed list of the browser compatibilities can be found here.
The good part is we can make basic maths directly:
let nuts = 7
more.innerHTML = `
<h2>You collected ${nuts} nuts so far!
<hr>
Double it, get ${nuts + nuts} nuts!!
`
<div id="more"></div>
It became really useful in a factory function:
function nuts(it){
return `
You have ${it} nuts! <br>
Cosinus of your nuts: ${Math.cos(it)} <br>
Triple nuts: ${3 * it} <br>
Your nuts encoded in BASE64:<br> ${btoa(it)}
`
}
nut.oninput = (function(){
out.innerHTML = nuts(nut.value)
})
<h3>NUTS CALCULATOR
<input type="number" id="nut">
<div id="out"></div>
It's a pretty useful functionality, for example here is a Node.js code snippet to test the set up of a 3 second timing function.
const waitTime = 3000;
console.log(`setting a ${waitTime/1000} second delay`);
Explanation
Declare wait time as 3000
Using the backtick you can embed the result of the calculation of 'wait time' divided by 1000 in the same line with your chosen text.
Further calling a timer function using the 'waitTime' constant will result in a 3 second delay, as calculated in the console.log argument.
You can make a template of templates too, and reach private variable.
var a= {e:10, gy:'sfdsad'}; //global object
console.log(`e is ${a.e} and gy is ${a.gy}`);
//e is 10 and gy is sfdsad
var b = "e is ${a.e} and gy is ${a.gy}" // template string
console.log( `${b}` );
//e is ${a.e} and gy is ${a.gy}
console.log( eval(`\`${b}\``) ); // convert template string to template
//e is 10 and gy is sfdsad
backtick( b ); // use fonction's variable
//e is 20 and gy is fghj
function backtick( temp ) {
var a= {e:20, gy:'fghj'}; // local object
console.log( eval(`\`${temp}\``) );
}
A lot of the comments answer most of your questions, but I mainly wanted to contribute to this question:
Is there a way in which the behavior of the backtick actually differs from that of a single quote?
A difference I've noticed for template strings is the disability to set one as an object property. More information in this post; an interesting quote from the accepted answer:
Template strings are expressions, not literals1.
But basically, if you ever wanted to use it as an object property you'd have to use it wrapped with square brackets.
// Throws error
const object = {`templateString`: true};
// Works
const object = {[`templateString`]: true};
The backtick character () *in JavaScript is used to define template literals. A template literal is a special type of string that allows you to embed expressions, which are evaluated and included in the final string. They are denoted by being surrounded by the backtick ()* character instead of single quotes (') or double quotes (").
Here's an example of using a template literal to embed an expression in a string:
const name = "Akila";
const message = `Hello, ${name}!`;
console.log(message); // Output: Hello, Akila!
In the example above, the expression ${name} is evaluated and included in the final string, which is assigned to the message variable.
Template literals also provide several convenient features, such as multi-line strings and string interpolation. Multi-line strings allow you to include line breaks in your strings, which is especially useful for creating formatted text.
Here's an example of using a multi-line string with a template literal:
const message = `This is a
multi-line string.`;
console.log(message);
output
This is a
multi-line string.
In conclusion, the backtick character (`) in JavaScript is used to define template literals, which are a convenient way to include expressions and multi-line strings in your JavaScript code.
This question already has answers here:
JavaScript Regex, where to use escape characters?
(3 answers)
Closed 8 years ago.
I'm unable to parse a regex. I've tested it from regexpal.com and regex101.com (by setting the expression as "(?:^csrf-token|;\s*csrf-token)=(.*?)(?:;|$)" and the test string as "__ngDebug=false; csrf-token=b2ssOJ4jNOlPdmXAHn4CORPvFoO4Ngsupej25tdj") where it works.
The example is jsfiddle.
function getCookie(name) {
var s = "__ngDebug=false; csrf-token=b2ssOJ4jNOlPdmXAHn4CORPvFoO4Ngsupej25tdj";
var regexp = new RegExp("(?:^" + name + "|;\s*"+ name + ")=(.*?)(?:;|$)", "g");
var result = regexp.exec(s);
return (result === null) ? null : result[1];
}
alert(getCookie("csrf-token"));
If however s is "csrf-token=b2ssOJ4jNOlPdmXAHn4CORPvFoO4Ngsupej25tdj", then it works fine. Please tell me what's wrong.
The expected output is "b2ssOJ4jNOlPdmXAHn4CORPvFoO4Ngsupej25tdj", and there is no input (the string to be tested is 's').
Change
"|;\s*"
to
"|;\\s*"
^
The thing is, you are constructing the RegExp by passing in a string via the constructor, so you need to follow the rule of escaping in string literal. In JavaScript, "\s" is recognized as a single character string, with lowercase s. To specify \, you need to escape it.
You should escape \s
var regexp = new RegExp("(?:^" + "csrf-token" + "|;\\s*"+ "csrf-token" + ")=(.*?)(?:;|$)", "g");
^
This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 8 years ago.
My code:
var string = "I put putty on the computer. putty, PUT do I"
var uniques = {};
var result = (string.match(/\b\w*put\w*\b/ig) || []).filter(function(item) {
item = item.toLowerCase();
return uniques[item] ? false : (uniques[item] = true);
});
document.write( result.join(", ") );
Here i want pass a variable inside the expression
here i have pass a value 'put' and get answer. But i have to use variable for this value.
I have tried string.match(/\b\w*{+put+}\w*\b/ig
Can you share your answers
You should create a specific Regular Expression object to use with the .match() function. This way you can create your regex with a string and insert the variable when creating it:
var changing_value = "put";
var re = new RegExp("\\b\\w*" + changing_value + "\\w*\\b", "ig");
Note that the ignore case (i) and global (g) modifiers are specified as the second parameter to the RegExp constructor instead of part of the actual expression. Also that you need to escape the \ character inside the constructor because \ is also an escape character in strings.
Another thing to note is that you don't need the /delimiters/ at the start and end of the expression when using the Regexp constructor.
Now you can use the Regexp object in your call to .match():
string.match( re )
As a final note, I don't recommend that you use the name string as a variable name... As you can see from the syntax highlighting, string is a reserved word and it is not recommended to use names of built-in types for variable names as they may cause confusion.