How do I concatenate two strings in javascript? - javascript

I want to concatenate two string in angular 7.
the function is:
getEmployment(id: number): Observable<Employment> {
const url = '${this.EmploymentUrl}/${id}';
return this.http.get<Employment>(url).pipe(
tap(_ => this.log('fetched employment id=${id}')),
catchError(this.handleError<Employment>('getEmployment id=${id}'))
);
}
However, when I inspect element in my web browser it shows that {id} is not found.
If I replace the second line with the following it works just fine.
const url = this.EmploymentUrl + '/' + id;
After a lot of googling I can't figure out why the first method doesn't work. Why doesn't it work and what is the difference between the two methods?

You should use `` instead of quotes. more info here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
getEmployment(id: number): Observable<Employment> {
const url = `${this.EmploymentUrl}/${id}`;
return this.http.get<Employment>(url).pipe(
tap(_ => this.log(`fetched employment id=${id}`)),
catchError(this.handleError<Employment>(`getEmployment id=${id}`))
);
}

Beacuase you are using quote (') instead backtick (`)
getEmployment(id: number): Observable<Employment> {
const url = `${this.EmploymentUrl}/${id}`;
return this.http.get<Employment>(url).pipe(
tap(_ => this.log('fetched employment id=${id}')),
catchError(this.handleError<Employment>('getEmployment id=${id}'))
);
}

The answer was simply that I have to use backpacks (`) instead of single quotes (')
Like so:
const url = `${this.EmploymentUrl}/${id}`;

Or you can just do a simple string concat like
const url:string = this.Employment+'/'+id; // id will be converted into a string

Related

Regex expression not returning anything after adding check for precision in input

im just trying to figure out why my input is not outputting anything after I added the precision check in my regex. It simply will not show anything in the input field after the precision check is added into the regex. I have looked for examples to dynamically render the precision value and it seems like it is something similar to what I have implemented in my code:
const handleAssetAmountFormat = (value) => {
if (value) {
const precision = transactionType === TRANSACTION_TYPES.BUY ? selectedBaseCurrencyObj.precision.cost : selectedBaseCurrencyObj.precision.amount;
const regex = new RegExp(`/^\d+\.?\d${precision}/`);
const result = value.match(regex);
if (result) {
return result[0];
}
}
return '';
};
const handleAssetAmount = (e) => {
const { value } = e.target;
const formattedAmount = handleAssetAmountFormat(value);
setFromCurrencyAmount(formattedAmount);
};
Anyone able to figure out what's going on here? Any help is appreciated. Thanks!
Three things are wrong:
You use a string literal, yet you use slashes, they should not be
there.
You should use double escape to escape your control characters.
You should add an extra pair of { } around the precision to act as
a quantifier.
This result in this regex, that should work:
const regex = new RegExp(`^\\d+\\.?\\d{${precision}}`);
Alternatively you could use String.Raw. Then you don't have to double escape. That would be:
const regex = new RegExp(String.raw`^\d+\.?\d{${precision}}`);
I don't know what are you trying to check but as far as I can tell normally a re starts with ^(caret) symbol and ends with an $ symbol but you are using a /(escape) character try using the escape characters outside of parentheses.

Splitting a URL by either of 2 different parts

Currently, my code splits the URL and removes anything after &7. How can I also make it check for |relevance at the same time and split by whichever one it sees?
$(document).ready(($) => {
const params = new URLSearchParams(window.location.search);
if (params.has("query")) {
const query = params.get("query").split('%7').pop();
$("#textfield").val(query);
}
});
I tried replacing
.split('%7').pop(); with .split('%7' || '|relevance').pop(); but that didn't work.
The or needs to be in regex format.
here is where you can test regex:
https://regex101.com/r/kQwpTN/1
const query = params.get("query").split(/%7|\|relevance/).pop();
Cheers!

Prevent URL.toString() from escaping plus (+) symbols

I want to write a method that takes an array of strings and joins them with a + symbol, similarily to what Google does. This is my method:
function getQueryUrl(array) {
let urlParamsString = array.join("+");
const url = new URL(window.location);
url.searchParams.set("query", urlParamsString);
return url.toString();
}
But instead of getting the cleanly plus-separated URL, the URL API escapes the symbols with %2B. Is there any way to prevent this (apart from straight-up replacing the escaped symbols back to +)?
Try unescape() function:
function getQueryUrl(array) {
let urlParamsString = array.join("+");
const url = new URL(window.location);
url.searchParams.set("query", urlParamsString);
return unescape(url.toString());
}
Update:
use decodeURIComponent(url.toString());

How to parse JSON-like file with regex

I have this structure of my input data, it is just like JSON but not containing strings. I only need to parse few information from these data
{ .appVersion = "1230"; DisplayStrings = ( A ); customParameters = ( { name = Axes;.......(continues)}'''
the code looks like this, what happens here is that it matches but search until last appearance of semicolon. I tried all non-greedy tips and tricks that I have found, but I feel helpless.
const regex = /.appVersion = (".*"?);/
const found = data.match(regex)
console.log(found)
How can I access value saved under .appVersion variable, please?
You need to escape the . before appVersion since it is a special character in Regex and you can use \d instead of .* to match only digits. If you want just the number to be captured, without the quotes you can take them out of the parentheses.
const regex = /\.appVersion = "(\d+)";/
const found = data.match(regex)
const appVersion = found[1];
const string = '{ .appVersion = "1230"; DisplayStrings = (...(continues)';
const appVersion = string.match(/\.appVersion\s*=\s*"([^"]+)"/)[1];
If that's what you need...
I'm not sure where the format you're trying to parse comes from, but consider asking (making) your data provider return json string, so you could easily invoke JSON.parse() which works in both node and browser environments.
You can try the following:
var data='{ .appVersion = "1230"; DisplayStrings = ( A ); customParameters = ( { name = Axes;.......(continues)}';
const regex = /.appVersion = [^;]*/ //regex test: https://regex101.com/r/urX53f/1
const found = data.match(regex);
var trim = found.toString().replace(/"/g,''); // remove the "" if necessary
console.log(found.toString());
console.log(trim);
Your regex is looking for . which is "any character" in a regex. Escape it with a backslash:
/\.appVersion = ("\d+");/
Don't use .* to capture the value, It's greedy.
You can use something like \"[^\"]* - Match a quote, then Any character except quote, as many time as possible.
try
const regex = \.appVersion = \"([^\"]*)\";
Note that the first dot is should also be quoted, and the spaces should be exactly as in your example.

conditional substring in JS

I have a function that should clean a string , actually I have two kind of string "SATISFACTION._IS1.TOUTES_SITUATIONS.current_month_note" or "SATISFACTION._IS1.TOUTES_SITUATIONS.note" .
PS for information TOUTES_SITUATIONS is variable
What I would return is "TOUTES_SITUATIONS"
Here's my code
const extractSituation: Function = (sentence: string): string => {
return sentence.substring(
sentence.lastIndexOf('1.') + 2,
sentence.lastIndexOf('.n'),
);
};
actually it handles only one type of sentence "SATISFACTION._IS1.TOUTES_SITUATIONS.note" but not "SATISFACTION._IS1.TOUTES_SITUATIONS.current_month_note"
How can I do to handle both of them ?
Array's index start from 0. Try something like this:
const extractSituation: Function = (sentence: string): string => {
return sentence.split('.')[2];
};
You might be able to just use a regex for this to pull out the text between the first SATISFACTION._IS1. and last .:
let s = "SATISFACTION._IS1.TOUTES_SITUATIONS.current_month_note"
let s2 = "SATISFACTION._IS1.TOUTES_someother.text__SITUATIONS.note"
let regex = /^SATISFACTION._IS1\.(.*)\..*$/
console.log(s.match(regex)[1])
console.log(s2.match(regex)[1])
I'm assuming:
1) You need to handle a general case where the 'situation' could be any string without periods.
2) The break before and after the 'situation' is delimited by '.'
You can retrieve the substring from the start of the situation to the end of the sentence, then find the index of the next '.' to find the substring containing only the situation.
const extractSituation: Function = (sentence: string): string => {
// sentence truncated up to start of situation
var situation = sentence.substring(sentence.lastIndexOf('1.') + 2);
// Up to the next period from start of situation
return situation.substring(0, situation.indexOf('.'));
};
This code only works given that you can assume every situation is preceded by your '1.' index.

Categories