I have tried checking this using the function str.includes('${') as a trivial solution but I am not receiving the correct output. I am also getting back the strings that do not include it.
An example string that would satisfy this condition is: 'My name is ${customer.Name} '
You can probably use Regex to find it. If you are just looking to see if a string just has a template literal in it you could do something like the following:
const str = 'My name is ${customer.Name} '
const regex = /\${(.*?)\}/g
const hasTemplateLiteral = (str) => str.search(regex) > -1
console.log(hasTemplateLiteral(str))
You can check the javascript regular expressions functions here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#using_regular_expressions_in_javascript. /\${(.*?)\}/g will check for the ${} with anything in between the brackets and return the index if it is found or return -1 if not found. You can test the regex here https://regexr.com/
Note this will only work if the template literal is actually in string format like your example above. If your template literal is in backticks then it will actually contain the variable. Then it won't work and you would then have to check if the string includes the variable that is in your template literal like so:
const customer = {Name: 'bob'}
const str = `My name is ${customer.Name}`
const regex = /\${(.*?)\}/g
const hasIncludedVariable = (str, v) => str.includes(v)
console.log(hasIncludedVariable(str, customer.Name))
Related
i have this string => someRandomText&ab_channel=thisPartCanChange and i want to delete all from & (inclusive) to the end [this part: &ab_channel=thisPartCanChange].
How can i do this?
You van try something like:
console.log("someRandomText&ab_channel=thisPartCanChange".split("&")[0])
const yourString = 'SomeRandomText&ab_channel=thisPartCanChange'
console.log(yourString.split('&ab_channel')[0])
I would do a regex replacement on &.*$ and replace with empty string.
var inputs = ["someRandomText&ab_channel=thisPartCanChange", "someRandomText"];
inputs.forEach(x => console.log(x.replace(/&.*$/, "")));
Note that the above approach is robust with regard to strings which don't even have a & component.
You can use substring which extract the characters between two specified index without changing the original string
const yourString = 'someRandomText&ab_channel=thisPartCanChange';
const newStr = yourString.substring(0, yourString.indexOf('&'));
console.log(newStr)
I have an array of string which looks like this:
ErrStr = [
\\abc\def\ghi; ,
\\klm\nop\qrs;
]
So, this array of strings will be dynamic, so what I want to extract is only the abc and klm from this array.
This piece of code is what joins the strings after filtering from the data:
let errorArr = filteredError.map(a => a.ErrStr.split('\\\\', '')).join('')
I tried the above code, it cuts the \\ and replaces with , but I am not able to figure out how do I remove the 2nd and 3rd part of the string. Thanks in advance.
Backslash in an Escape character in Javascript and has special meaning. To literally use it you need to, well, escape it beforehand with another backslash
const str1 = "\a";
console.log(str1); // "a" Where's my backslash?
const str2 = "\\a";
console.log(str2); // "\a" Aha, here it is
Therefore, first make sure your array has Strings (which currently what you provided are not strings therefore it's an invalid JSON)
And use:
const arr = [
"\\\\abc\\def\\ghi;",
"\\\\klm\\nop\\qrs;",
];
const codes = arr.map(s => /(?<=^\\\\)[^\\]+/.exec(s)).flat()
console.log(codes); // ["abc", "klm"]
Overview example on Regex101.com
I have a regular expression and would like to put a variable inside it. How do I do?
My code is this:
public regexVariable(vRegex: string, testSentences: Array<any> ) {
const regex = new RegExp('/^.*\b(' + vRegex + ')\b.*$/');
const filterSentece = testSentences.filter(result => {
if (regex.test(result)) {
return result
})
}
const regex = new RegExp(`^.*\\b(${vRegex})\\b.*$`);
You can use template literals (`, instead of "/') to build strings that you can interpolate expresions into; no more oldschool +ing.
The only thing that was an actual issue with your code, though, was the \b character class. This sequence is what you want RegExp to see, but you can't just write that, otherwise you're sending RegExp the backspace character.
You need to write \\b, which as you can see from that link, will make a string with a \ and an ordinary b for RegExp to interpret.
You're almost there, just look at RegEx constructor
const regex = new RegExp('^.*\\b(' + vRegex + ')\\b.*$');
i want to replace multiple patterns in the same string using regex and javascript.
What i am trying to do?
i have a string for example
string = "hello i am [12#fname lname] and i am referring this user [23#fname1 lname1]"
now i get all the strings with [] using regex
const get_strings_in_brackets = string.match(/\[(\d+#[\w\s]+)]/g);
so get_strings_in_brackets will have
["[12#fname lname]", "[23#fname1 lname1]"]
now i want these to be replaced with string "<some-tag id="12"/> "<some-tag id="23"/> in the string "hello i am [12#fname lname] and i am referring this user [23#fname1 lname1]"
also this number 12 in this string "<some-tag id="12"/> is got from the string ["[12#fname lname]" before # character.
What i have tried to do?
i have tried to replace for only one string withing brackets meaning for the example below
string ="hello i am [12#fname lname1]"
const extracted_string_in_brackets = string.match(/\[(\d+#[\w\s]+)]/g);
const get_number_before_at_char =
extracted_string_in_brackets[0].substring(1,
extracted_string_in_brackets[0].indexOf('#'));
const string_to_add_in_tag = `<some-tag
id="${get_number_before_at_char}"/>`;
const final_string = string.replace(extracted_string_in_brackets,
string_to_add_in_tag);
The above code works if i have only one string within square brackets. But how do i do it with multiple strings in brackets and replacing that with tag string that is for example .
Could someone help me solve this. thanks.
Just use a group reference in your replacement:
string = "hello i am [12#fname lname] and i am referring this user [23#fname1 lname1]"
newstr = string.replace(/\[(.+?)#(.+?)\]/g, '<some-tag id="$1"/>')
console.log(newstr)
I have a string which represents the attributes of a function:
str = "'MyCommunities', null, {'viewAllLink':'https://cpkornferrybruceapidev.azurewebsites.net', 'clientId':'078c49af-bb40-44c3-a685-539a84cc5de7', 'subscriptionId':'64fc6f58-2a67-472b-b57f-f0f5441e7992'}"
There are 3 attributes: My Communities, null, {...}
I would like to split the string into array containing these 3 values but without splitting the object literal.
I believe I need to construct a regular expression which would allow me to str.split(//) however I am not able to get the 3 attributes which I need.
Any help would be appreciated.
If be sure the string doesn't have extra ' in the value of each element, I think one quick way is treat it as one JSON string, then pull out the element you need.
The codes are like below:
let str = "'MyCommunities', null, {'viewAllLink':'https://cpkornferrybruceapidev.azurewebsites.net', 'clientId':'078c49af-bb40-44c3-a685-539a84cc5de7', 'subscriptionId':'64fc6f58-2a67-472b-b57f-f0f5441e7992'}"
console.log(JSON.parse('[' + str.replace(/'/g, '"') +']'))
If you don't have nested braces and if comma is always before {, then you can do this:
var re = /(\{[^}]+\})/;
var result = [];
str.split(re).forEach(function(part) {
if (part.match(re) {
result.push(part);
} else {
var parts = part.split(',').map((x) => x.trim()).filter(Boolean);
result = result.concat(parts);
}
});
if you have something before braces or if braces are nested you will need more compicated parser.
My first suggestion would be to find a different way to get the string formatted coming into your system. If that is not feasible, you can do the following regex (note: it is super fragile):
/\,(?![^{]*})/
and get the groupings like so:
list = str.split(/\,(?![^{]*})/)
I would use the second limit parameter of split() (docs) to stop cutting before the object literal:
var str = "'MyCommunities', null, {'viewAllLink':'https://cpkornferrybruceapidev.azurewebsites.net', 'clientId':'078c49af-bb40-44c3-a685-539a84cc5de7', 'subscriptionId':'64fc6f58-2a67-472b-b57f-f0f5441e7992'}";
console.log(str.split(', ', 3));