Regular expression in JavaScript that matches ${} - javascript

I want regular expressions to match string that starts with either ${ , "${ , '${ and ends with } , }' , }". My string may be ${anythinghere}, "${anythinghere}", '${anythinghere}'. I tried with the following
var str = "${a}";
var patt = /^("|'|${)*(}|'|")$/;
var res = patt.test(str);
alert(res);
But my above code always returns false.

You have to escape the inner $ with a backslash, since it's a special character. But that alone won't fix the problem. As it is above, patt matches any string that begins with " or ' or ${, 0 or more times, and ends with } or ' or ". The regular expression that you want would be something like this:
var str = "${a}";
var patt = /^(['"]?)\${.*}\1$/;
var res = patt.test(str);
alert(res);
Here is what each part of patt is doing:
^(['"]?): The string must begin with 0 or 1 single quote, or with 0 or 1 double quote. This is in parentheses so that we can reference it at the end of the regexp
\${: Next must be a dollar sign followed by an open curly bracket
.*: Next must be 0 or more of any character (other than a newline)
}: Next must be a closed curly bracket
\1$: Finally, the string must end with whatever pattern was matched at the beginning of the string. \1 is a "back-reference" to the first capturing group (in the parentheses), so if the string began with a single quote, it will only match if it also ends with a single quote. Same goes for double quotes, and no quotes at all

$ has a special meaning in regex, so it must be escaped using a backslash \. If you want 1 or more wildcards, that's represented with a .+, not a *. The following code will match the test pattern:
/^'?"?\${.+}'?"?$/

You can use
var a=new RegExp("\^(\'\\$\{)[a-z]+(\}\')|(\"\\$\{)[a-z]+(\}\")|(\\$\{)[a-z]+(\})\$");
a.test("${vijay}")//true
a.test("\'${vijay}\'")//true
a.test("\"${vijay}\"")//true
a.test("\'${vijay}\"")//false
If you use only \$ it takes as end og expresion.So use\\$ means $ as a special character

This works:
var str = "\"${a}\"";
var patt = /^\"\$\{((?!\").)+\}\"$/;
var res = patt.test(str);
alert(res);
Note that the value assigned to str has been changed to \"${a}\" in order to reflect what you stated targets. You must escape (put a backslash before) any character you wish to be read literally and not as a metacharacter. In order to have this match any one of your targets at once, simply repeat the pattern in patt three times, separated by pipes as usual, replacing the \" with \' or nothing at all (in which case, you should change the \" inside the inner most parenthesis to }). These changes are shown below:
var patt = /^\"\$\{((?!\").)+\}\"$|^\'\$\{((?!\').)+\}\'$|^\$\{((?!\}).)+\}$/;

Related

Javascript: Remove trailing chars from string if they are non-numeric

I am passing codes to an API. These codes are alphanumeric, like this one: M84.534D
I just found out that the API does not use the trailing letters. In other words, the API is expecting M84.534, no letter D at the end.
The problem I am having is that the format is not the same for the codes.
I may have M84.534DAC, or M84.534.
What I need to accomplish before sending the code is to remove any non-numeric characters from the end of the code, so in the examples:
M84.534D -> I need to pass M84.534
M84.534DAC -> I also need to pass M84.534
Is there any function or regex that will do that?
Thank you in advance to all.
You can use the regex below. It will remove anything from the end of the string that is not a number
let code = 'M84.534DAC'
console.log(code.replace(/[^0-9]+?$/, ""));
[^0-9] matches anything that is not a numer
+? Will match between 1 and unlimited times
$ Will match the end of the string
So linked together, it will match any non numbers at the end of the string, and replace them with nothing.
You could use the following expression:
\D*$
As in:
var somestring = "M84.534D".replace(/\D*$/, '');
console.log(somestring);
Explanation:
\D stands for not \d, the star * means zero or more times (greedily) and the $ anchors the expression to the end of the string.
Given your limited data sample, this simple regular expression does the trick. You just replace the match with an empty string.
I've used document.write just so we can see the results. You use this whatever way you want.
var testData = [
'M84.534D',
'M84.534DAC'
]
regex = /\D+$/
testData.forEach((item) => {
var cleanValue = item.replace(regex, '')
document.write(cleanValue + '<br>')
})
RegEx breakdown:
\D = Anything that's not a digit
+ = One or more occurrences
$ = End of line/input

How can I remove newline characters at the beginning and ending of a string?

I am having string as below:
var str = "\ncat\n"
from the above string i want the output to be
str = "cat"
Is there any best way to do that?
You need to trim the whitespace characters around the string, with String.prototype.trim, like this
console.log("\ncat\n".trim());
// cat
You can also remove all the whitespace characters in the beginning and ending of the string using a regular expression, like this
console.log("\t\t\t \r\ncat\t\r\n\r".replace(/^\s+|\s+$/g, ''));
// cat
The regular expression means that match one or more whitespace characters (\s means whitespace characters) at the beginning of the string (^ means beginning of the string) or at the end of the string ($ means the end of string). The + after \s means that match one or more times. The g after / means global match, it actually makes the RegEx match more than once. So, whenever the match is found, it will be replaced with an empty string.
You should look at the substr function. In your case, you could do:
var string = '\ncat\n';
document.write(string.substr(1, string.length - 2));

Return string between square brackets and slashes inside

How to return string/values between square brackets and slashes inside like :
var valueX = "[/This is Value/]"
After catch, I need result : This is Value.
Thanks for your help.
Use a Regular Expression:
var valueX = "[/This is value/]";
valueX.replace(/^\[\/(.*)\/\]$/, '$1');
Breaking it down, ^ matches the start of the line. \[\/ matches the initial [/; the backslashes are to stop them being interpreted as special characters. (.*) means match zero or more * of any character . and save it as a group (). \/\] is the final /], and $ matches the end of the line. The $1 in the replacement string tells it to use the first matched group, in our case the zero or more of any character.
Using replace :
'[/This is value/]'.replace(/\[\/(.*?)\/\]/, '$1'); // "This is value"
Use the global flag (//g) to replace all occurences :
'[/a/] [/b/] [/c/] [//]'.replace(/\[\/(.*?)\/\]/g, '$1'); // "a b c "

Replace special chars in between only, not start and end of the string?

I need to replace special character '(apostrope) with \'(back slash apostrope) but this should be only in between the string except starting and ending characters of the string.
eg: msg ='My Son's Daughter';
There can be multiple apostropes in the string. I just want to replace apostropes in the string which are not starting and ending characters.
Please share me any ideas.
Using a combination of substr() and regex:
var msg ="'My Son's Daughter'";
msg = msg.substr(0, 1) + msg.substr(1, msg.length-2).replace(/'/g, "\\'") + msg.substr(msg.length-1, 1);
Outputs:
'My Son\'s Daughter'
As shown, only the inner ' are replaced, the first and last are ignored.
Try
msg = msg.replace(/(.)'(.)/g, "$1\\'$2");
The . at beginning and end will require any character before and after the '.
The () will catch that charachter defined in it (.) to a variable ($1 and $2).
The $1 and $2 represent the catched character of both ().
The \\ escapes/represents a literal \
The / at the start, just before the g defines this as a Regular Expression (regex)
The g is a modifier (global) that will indicate ALL occurrences.
The regex should NOT be put between quotes as if it was a string.
The replace function is what you're after. This should do the trick:
msg = msg.replace(/'/g, "\\'");

how to regex a string between two tokens in Javascript?

Asked many times, but I can't get it to work...
I have strings like:
"text!../tmp/widgets/tmp_widget_header.html"
and am trying like this to extract widget_header:
var temps[i] = "text!../tmp/widgets/tmp_widget_header.html";
var thisString = temps[i].regexp(/.*tmp_$.*\.*/) )
but that does not work.
Can someone tell me what I'm doing wrong here?
Thanks!
This prints widget_header:
var s = "text!../tmp/widgets/tmp_widget_header.html";
var matches = s.match(/tmp_(.*?)\.html/);
console.log(matches[1]);
var s = "text!../tmp/widgets/tmp_widget_header.html",
re = /\/tmp_([^.]+)\./;
var match = re.exec(s);
if (match)
alert(match[1]);
This will match:
a / character
the characters tmp_
one or more of any character that is not the . character. These are captured.
a . character
If a match was found, it will be at index 1 of the resulting Array.
In your code:
var temps[i] = "text!../tmp/widgets/tmp_widget_header.html";
var thisString = temps[i].regexp(/.*tmp_$.*\.*/) )
You are saying:
"Match any string that starts with any number of any characters, followed by "tmp_", followed by the end of input, followed by any number of periods."
.* : Any number of any character (except newline)
tmp_ : Literally "tmp_"
$ : End of input/newline - this will never be true in this position
\. : " . ", a period
\.* : Any number of periods
Plus when using the regex() function you need to pass a string, using string notation like var re = new RegExp("ab+c") or var re = new RegExp('ab+c') not in regex notation using slash. You also have either an extra, or missing parenthesis, and no characters are actually being captured.
What you want to do is:
"Find a string that preceded by the begining of input, followed by one or more of any character, followed by "tmp_"; followed by a single period, followed by one or more of any character, followed by the end of input;t that contains one or more of any character. Capture that string."
So:
var string = "text!../tmp/widgets/tmp_widget_header.html";
var re = /^.+tmp_(.+)\..+$/; //I use the simpler slash notation
var out = re.exec(string); //execute the regex
console.log(out[1]); //Note that out is an array, the first (here only) catpture sting is at index 1
This regex /^.+tmp_(.+)\..+$/ means:
^ : Match beginning of input/line
.+ : One or more of any character (except newline), "+" is one or more
tmp_ : Constant "tmp_"
\. : A single period
.+ : As above
$ : End of input/line
You could also use this as RegEx('^.+tmp_(.+)\..+$'); not that when we use RegEx(); we do not have the slash marks, instead we use quote marks (single or double will work), to pass it as a string.
Now this would also match var string = "Q%$#^%$^%$^%$^43etmp_ebeb.45t4t#$^g" and out == 'ebeb'. So depending on the specific use you may wish to replace any " . " used to signify any character (except newline) with bracketed "[ ]" character lists, as this may filter out unwanted results. You milage may vary.
For more information visit: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions

Categories

Resources