I've got the string variable, containing the folowing text:
var val1="GES3 02R202035 ";
var val2=0;
var val3="06 ";
var val4="03.01.11i";
var val5="";
I want to use RegExp to get the array of values and filter values from trailing spaces also.
/="?([\w\s\.]*)/g helps alot, except trailing spaces, and i'm not sure about other charachters there could be.
So I need something like /="?(.*);/g but it doesn't remove last " and spaces also.
/="?(.*)"?;/g doesn't remove last ", who know why?
Could please anybody help me with this?
Edit:
The expected output is:
GES3 02R202035
0
06
03.01.11i
and empty string here
Edit:
I need this in javascript (node.js) str.match(/?????/);
Edit: With the help of Wiktor Stribiżew and melpomene finally I came to:
(notice lookbehind in regex, it will work in chrome with harmony flag enabled only)
var str =
'var val1="GES3 02R202035 ";\n' +
'var val2=0;\n' +
'var val3="06 ";\n' +
'var val4="03.01.11i";\n' +
'var val5="";\n';
console.log('before:\n' + str);
var parts = str.match(/(?<=="?)[^"]*?(?=\s*"?;)/g);
console.log('parts\n', parts);
The problem with str.match() was that it return array of matches, and I actually need array of groups. The solution was to arrange RegEx to match exactly the result what I need. It became possible with the latest V8 and its support of lookbehind.
var str =
'var val1="GES3 02R202035 ";\n' +
'var val2=0;\n' +
'var val3="06 ";\n' +
'var val4="03.01.11i";\n' +
'var val5="";\n';
console.log('before:\n' + str);
var re = /=\s*(?:([-+]?\d+(?:\.\d+)?)|"([^"]*)")/g;
var parts = [];
var m;
while (m = re.exec(str)) {
var x =
m[1] !== undefined
? Number(m[1])
: m[2].trim()
parts.push(x);
}
console.log('parts\n', parts);
This code extracts the embedded numbers and strings (after a = sign). Numbers (in the format (- | +)? digits (. digits)?, i.e. an optional sign and optional decimal places are accepted) are converted to JS numbers; strings have their contents extracted and trimmed.
It does not support exponential notation (1e2) or backslash escapes in strings.
Related
I'm trying to extract out a group of words from a larger string/cookie that are separated by hyphens. I would like to replace the hyphens with a space and set to a variable. Javascript or jQuery.
As an example, the larger string has a name and value like this within it:
facility=34222%7CConner-Department-Store;
(notice the leading "C")
So first, I need to match()/find facility=34222%7CConner-Department-Store; with regex. Then break it down to "Conner Department Store"
var cookie = document.cookie;
var facilityValue = cookie.match( REGEX ); ??
var test = "store=874635%7Csomethingelse;facility=34222%7CConner-Department-Store;store=874635%7Csomethingelse;";
var test2 = test.replace(/^(.*)facility=([^;]+)(.*)$/, function(matchedString, match1, match2, match3){
return decodeURIComponent(match2);
});
console.log( test2 );
console.log( test2.split('|')[1].replace(/[-]/g, ' ') );
If I understood it correctly, you want to make a phrase by getting all the words between hyphens and disallowing two successive Uppercase letters in a word, so I'd prefer using Regex in that case.
This is a Regex solution, that works dynamically with any cookies in the same format and extract the wanted sentence from it:
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Demo:
var str = "facility=34222%7CConner-Department-Store;";
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Explanation:
Use this Regex (/([A-Z][a-z]+)-?/g to match the words between -.
Replace any - occurence in the matched words.
Then just join these matches array with white space.
Ok,
first, you should decode this string as follows:
var str = "facility=34222%7CConner-Department-Store;"
var decoded = decodeURIComponent(str);
// decoded = "facility=34222|Conner-Department-Store;"
Then you have multiple possibilities to split up this string.
The easiest way is to use substring()
var solution1 = decoded.substring(decoded.indexOf('|') + 1, decoded.length)
// solution1 = "Conner-Department-Store;"
solution1 = solution1.replace('-', ' ');
// solution1 = "Conner Department Store;"
As you can see, substring(arg1, arg2) returns the string, starting at index arg1 and ending at index arg2. See Full Documentation here
If you want to cut the last ; just set decoded.length - 1 as arg2 in the snippet above.
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1)
//returns "Conner-Department-Store"
or all above in just one line:
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1).replace('-', ' ')
If you want still to use a regular Expression to retrieve (perhaps more) data out of the string, you could use something similar to this snippet:
var solution2 = "";
var regEx= /([A-Za-z]*)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/;
if (regEx.test(decoded)) {
solution2 = decoded.match(regEx);
/* returns
[0:"facility=34222|Conner-Department-Store",
1:"facility",
2:"34222",
3:"Conner-Department-Store",
index:0,
input:"facility=34222|Conner-Department-Store;"
length:4] */
solution2 = solution2[3].replace('-', ' ');
// "Conner Department Store"
}
I have applied some rules for the regex to work, feel free to modify them according your needs.
facility can be any Word built with alphabetical characters lower and uppercase (no other chars) at any length
= needs to be the char =
34222 can be any number but no other characters
| needs to be the char |
Conner-Department-Store can be any characters except one of the following (reserved delimiters): :/?#[]#;,'
Hope this helps :)
edit: to find only the part
facility=34222%7CConner-Department-Store; just modify the regex to
match facility= instead of ([A-z]*)=:
/(facility)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/
You can use cookies.js, a mini framework from MDN (Mozilla Developer Network).
Simply include the cookies.js file in your application, and write:
docCookies.getItem("Connor Department Store");
I have a textarea that will have one or more pairings that look like this,
Lat = 38.7970308
Long = -100.8665928
How can I extract the numbers using Javascript (negative sign included if there)? I want all the numbers listed.
You can use this regex:
var s ='Lat = 38.7970308\n' +
'Long = -100.8665928';
var m = s.match(/[+-]?(?:\d+(?:\.\d+)?|\.\d+)/g);
//=> ["38.7970308", "-100.8665928"]
Try this regex:
[\+\-]?\d+.?\d+$
/([+-]?(?:[0-9]+\.)?[0-9]+)/g
http://regex101.com/r/mC0yO2/1
You can use this pattern to basically extract all the numbers:
/-?\d+(?:\.\d+)?/g
If, as in your string example, you want to extract these numbers by pairs, you need to use capturing groups:
/^Lat = (-?\d+(?:\.\d+)?)\s*?\r?\nLong = (-?\d+(?:\.\d+)?)\s*?$/mg
for each pairs founded, the latitude is in the capture group 1 and the longitude in the capture group 2.
Note that this second pattern take in account that literal strings "Lat = " and "Long = " are at the start of a line, always in this order, and only separated by a newline character. (with the m modifier, ^ means "start of the line, and $ means "end of the line"). Trailing spaces are allowed with \s*? for each line.
Example:
var yourString = "Lat = 38.7970308\nLong = -100.8665928";
var myRe = /^Lat = (-?\d+(?:\.\d+)?)\s*?\r?\nLong = (-?\d+(?:\.\d+)?)\s*?$/mg;
var m;
while ((m = myRe.exec(yourString)) !== null) {
console.log(m[1] + "\t" + m[2]+ "\n\n");
}
Hi all ia m trying to replace all characters of "+" in a string by using the code below:
var findValue = "+";
var re = new RegExp(findValue, 'g');
searchValueParam = searchValueParam.replace(re, " ");
However i recieve this exception:
SyntaxError: Invalid regular expression: nothing to repeat
previously i applied just searchValueParam = searchValueParam.replace("+", " "); but that only replaces the first occurrence, not all.
Any suggestions?
For multiple replacements you need to use regex with the global (g) modifier, however + has a special meaning (the previous item 1 or more times), so it needs to be escaped.
searchValueParam = searchValueParam.replace(/\+/g,' ');
You need to escape the + sign:
searchValueParam.replace(/\+/g, " ");
If you want to keep the code you have, replace
var findValue = '+';
with
var findValue = '\\+';
Plus has a special meaning (quantifier) in a regular expression. This is why we need to escape it with a backslash: \+. However, when you place this in a string, the backslash itself has to be escaped as it has a special meaning in a string. This is how we end up with '\\+'.
In conclusion, this
var re = new RegExp('\\+', 'g')
is equivalent to this
var re = /\+/g;
This question already has answers here:
JavaScript regex pattern concatenate with variable
(3 answers)
Closed 4 years ago.
I am trying to create a regular expression with a character class that has a specific quantifier which is a variable for example:
var str = "1234.00";
var quantifier = 3;
str = str.replace(/(\d)(\d{quantifier}\.)/,"$1,$2");
//str should be "1,234.00"
This works as follows (without a variable):
var str = "1234.00";
str = str.replace(/(\d)(\d{3}\.)/,"$1,$2");
//str == "1,234.00"
However it does not have the same functionality with a quoted pattern instead of a slash-delimited pattern as follows:
var str = "1234.00";
str = str.replace("(\d)(\d{3}\.)","$1,$2");
//str == "1234.00" - not "1,234.00"
//quote symbol choice does not change this
str = str.replace('(\d)(\d{3}\.)',"$1,$2");
//str == "1234.00" - not "1,234.00"
edit: to be more clear I have added a summary question which was answered below:
How do I create a regular expression with an interpolated variable from a quoted string?
Although my preference would be to use interpolation, it seems that is not available (at least in this context), and is not necessary.
I have also tried to come up with a way to concatenate/join some regex literals to achieve the same result, but have been unable to do so for this use case.
As a side note - I am familiar with this type of regular expression in perl:
my $str = "1234.00";
my $quantifier = 3;
$str =~ s/(\d)(\d{$quantifier}\.)/$1,$2/;
# $str eq "1,234.00"
Which can be made useful as follows:
my $str = "1234567890.00";
for my $quantifier (qw(9 6 3)) {
$str =~ s/(\d)(\d{$quantifier}\.)/$1,$2/;
}
# $str eq "1,234,567,890.00"
With the suggestions/answers provided I have created a sample currency string prototype as follows:
String.prototype.toCurrency = function() {
var copy = parseFloat(this).toFixed(2);
for (var times = parseInt(copy.length/3); times > 0; times--) {
var digits = times * 3;
var re = new RegExp("(\\d)(\\d{" + digits + "}\\.)");
copy = copy.replace(re,"$1,$2");
}
return '$'+copy;
};
str = "1234567890";
str.toCurrency();
// returns "$1,234,567,890.00"
There are two problems with this statement:
str.replace("(\d)(\d{3}\.)","$1,$2");
The first is that you are passing a string and not a regular expression object, and the second is that within a string literal the backslash has a special meaning to escape certain things (e.g., "\n" is a newline) so to have an actual backslash in your string literal you need to double it as "\\". Using the RegExp() constructor to create a regex object from a string you get this:
str.replace(new RegExp("(\\d)(\\d{3}\\.)"),"$1,$2");
So from there you can do this:
var quantifier = 3
str = str.replace(new RegExp("(\\d)(\\d{" + quantifier + "}\\.)"),"$1,$2");
In JavaScript, you can't concatenate or interpolate into regex literals, but you can create a regex from a string by using the RegExp constructor:
str = str.replace(new RegExp('(\\d)(\\d{' + quantifier + '}\\.'), "$1,$2");
Note, by the way, that this:
str.replace(..., ...);
has no effect, because replace doesn't modify a string, but rather, it returns a copy of the string with the replacements made. So you need to write this:
str = str.replace(..., ...);
instead.
You can create a RegExp object:
var str = "1234.00";
var digits = 2;
var re = new RegExp("(\\d)(\\d{" + digits + "})");
var str2 = str.replace(re,"$1,$2-");
str2 would contain 1,23-4.00.
Working example:
http://jsfiddle.net/JuZtc/
Note that you need to escape \ in strings, thus \\.
Hope this helps.
I am getting this value from DatePicker
var datepickr = 'Jun-29-2011';
I want to replace underscores(-) with space .
I tried this way , but it isn't working
var b = datepickr.replace("-",' ');
Just for reference:
var datepickr = 'Jun-29-2011';
datepickr.replace("-", " "); // returns "Jun 29-2011"
datepickr.replace(/-/, " "); // returns "Jun 29-2011"
datepickr.replace(/-/g, " "); // returns "Jun 29 2011" (yay!)
The difference is the global modifier /g, which causes replace to search for all instances. Note also that - must be escaped as \- when it could also be used to denote a range. For example, /[a-z]/g would match all lower-case letters, whereas /[a\-z]/g would match all a's, z's and dashes. In this case it's unambiguous, but it's worth noting.
EDIT
Just so you know, you can do it in one line without regex, it's just impressively unreadable:
while (str !== (str = str.replace("-", " "))) { }
.replace is supposed to take a regular expression:
var b = datepickr.replace(/-/g,' ');
I'll leave it as an exercise to the reader to research regular expressions to the full.
(The important bit here, though, is the flag /g — global search)
Try this:
var datepickr = 'Jun-29-2011';
var b = datepickr.replace( /-/g, ' ' );
The /g causes it to replace every -, not just the first one.
var b = 'Jun-29-2011'.replace(/-/g, ' ');
Or:
var b = 'Jun-29-2011'.split('-').join(' ');
replace works with regular expressions, like so:
> "Hello-World-Hi".replace(/-/g, " ")
Hello World Hi
try:
var b = datepickr.toString().replace("-",' ');
I suspect that you are trying to replace chars inside a Date object.