Related
I would like to get all possible matches of a string with forward slashes '/' using regex.
I would like to regex that matches all the possibilities of a string between slashes but excludes a part which has no ending '/'
For example a string /greatgrandparent/grandparent/parent/child
it should return something like this:
/greatgrandparent/
/greatgrandparent/grandparent/
/greatgrandparent/grandparent/parent/
The following regex that will get each word that begins with a / and a positive lookahead for the / character is this /\/\w+(?=\/)/g
You can use the match() function that will place each word it finds in an array. You can then loop through the array to combine the different results. Check out the snippet below.
var str = `/greatgrandparent/grandparent/parent/child`;
var strArr = str.match(/\/\w+(?=\/)/g);
console.log(strArr);
var strLoop = ``;
for (i = 0; i < strArr.length; i++) {
strLoop += strArr[i];
document.write(`${strLoop}<br>`);
}
I am creating a script of time calculation from MySQL as I don't want to load the scripts on server-side with PHP.
I am getting the data and parsing it using JSON, which gives me a string of values for column and row data. The format of this data looks like:
1548145153,1548145165,End,Day;1548145209,1548145215,End,Day;1548148072,1548148086,End,Day;1548161279,1548161294,End,Day;1548145161,1548145163,End,Day;1548148082,1548148083,End,Day;1548161291,1548161293,End,Day
I need to split this string by semi-colon, and then extract the first VARCHAR number from before each comma to use that in subsequent calculation.
So for example, I would like to extract the following from the data above:
[1548145153, 1548145209, 1548148072, 1548161279, 1548145161, 1548148082, 1548161291]
I used the following type of for-loop but is not working as I wanted to:
for (var i=0; i < words.length; i++) {
var1 = words[i];
console.log(var1);
}
The string and the for-loop together are like following:
var processData = function(data) {
for(var a = 0; a < data.length; a++) {
var obj = data[a];
var str= obj.report // something like 1548145153,1548145165,End,Day;1548145209,1548145215,End,Day;1548148072,1548148086,End,Day;1548161279,1548161294,End,Day;1548145161,1548145163,End,Day;1548148082,1548148083,End,Day;1548161291,1548161293,End,Day
words = str.split(',');
words = str.split(';');
for (var i=0; i < words.length; i++) {
var1 = words[i];
var2 = var1[0];
console.log(var2);
}
Here is an approach based on a regular expression:
const str = "1548145153,1548145165,End,Day;1548145209,1548145215,End,Day;1548148072,1548148086,End,Day;1548161279,1548161294,End,Day;1548145161,1548145163,End,Day;1548148082,1548148083,End,Day;1548161291,1548161293,End,Day";
const ids = str.match(/(?<=;)(\d+)|(^\d+(?=,))/gi)
console.log(ids)
The general idea here is to classify the first VARCHAR value as either:
a number sequence directly preceded by a ; character (see 1 below) or, for the edge case
the very first number sequence of the input string directly followed by a , character (see 2 below).
These two cases are expressed as follows:
Match any number sequence that is preceded by a ; using the negated lookbehind rule: (?<=;)(\d+), where ; is the character that must follow a number sequence \d+ to be a match
Match any number sequence that is the first number sequence of the input string, and that has a , directly following it using the lookahead rule (^\d+(?=,)), where \d+ is the number sequence and , is the character that must directly follow that number sequence to be a match
These building blocks 1 and 2 are combined using the | operator to achieve the final result
First thing is that you override words with the content of str.split(';'), so it won't hold what you expect. To split the string into chunks, split by ; first, then iterate over the resulting array and within the loop, split by ,.
const str= "1548145153,1548145165,End,Day;1548145209,1548145215,End,Day;1548148072,1548148086,End,Day;1548161279,1548161294,End,Day;1548145161,1548145163,End,Day;1548148082,1548148083,End,Day;1548161291,1548161293,End,Day";
const lines = str.split(';');
lines.forEach(line => {
const parts = line.split(',');
console.log(parts[0]);
});
What you are doing is not correct, you'll have to separate strings twice as there are two separators. i.e. a comma and a semicolon.
I think you need a nested loop for that.
var str = "1548145153,1548145165,End,Day;1548145209,1548145215,End,Day;1548148072,1548148086,End,Day;1548161279,1548161294,End,Day;1548145161,1548145163,End,Day;1548148082,1548148083,End,Day;1548161291,1548161293,End,Day"
let words = str.split(';');
for (var i=0; i < words.length; i++) {
let varChars = words[i].split(',');
for (var j=0; j < varChars.length; i++)
console.log(varChars[j]);
}
I hope this helps. Please don't forget to mark the answer.
Given this query string:
?cgan=1&product_cats=mens-jeans,shirts&product_tags=fall,classic-style&attr_color=charcoal,brown&attr_size=large,x-small&cnep=0
How can I extract the values from only these param types 'product_cat, product_tag, attr_color, attr_size' returning only 'mens-jeans,shirts,fall,classic-style,charcoal,brown,large,x-small?
I tried using a non-capturing group for the param types and capturing group for just the values, but its returning both.
(?:product_cats=|product_tags=|attr\w+=)(\w|,|-)+
You can collect tha values using
(?:product_cats|product_tags|attr\w+)=([\w,-]+)
Mind that a character class ([\w,-]+) is much more efficient than a list of alternatives ((\w|,|-)*), and we avoid the issue of capturing just the last single character.
Here is a code sample:
var re = /(?:product_cats|product_tags|attr\w+)=([\w,-]+)/g;
var str = '?cgan=1&product_cats=mens-jeans,shirts&product_tags=fall,classic-style&attr_color=charcoal,brown&attr_size=large,x-small&cnep=0';
var res = [];
while ((m = re.exec(str)) !== null) {
res.push(m[1]);
}
document.getElementById("res").innerHTML = res.join(",");
<div id="res"/>
You can always use a jQuery method param.
You can use following simple regex :
/&\w+=([\w,-]+)/g
Demo
You need to return the result of capture group and split them with ,.
var mystr="?cgan=1&product_cats=mens-jeans,shirts&product_tags=fall,classic-style&attr_color=charcoal,brown&attr_size=large,x-small&cnep=0
";
var myStringArray = mystr.match(/&\w+=([\w,-]+)/g);
var arrayLength = myStringArray.length-1; //-1 is because of that the last match is 0
var indices = [];
for (var i = 0; i < arrayLength; i++) {
indices.push(myStringArray[i].split(','));
}
Something like
/(?:product_cats|product_tag|attr_color|attr_size)=[^,]+/g
(?:product_cats|product_tag|attr_color|attr_size) will match product_cats or product_tag or attr_color or attr_size)
= Matches an equals
[^,] Negated character class matches anything other than a ,. Basically it matches till the next ,
Regex Demo
Test
string = "?cgan=1&product_cats=mens-jeans,shirts&product_tags=fall,classic-style&attr_color=charcoal,brown&attr_size=large,x-small&cnep=0";
matched = string.match(/(product_cats|product_tag|attr_color|attr_size)=[^,]+/g);
for (i in matched)
{
console.log(matched[i].split("=")[1]);
}
will produce output as
mens-jeans
charcoal
large
There is no need for regular expressions. just use splits and joins.
var s = '?cgan=1&product_cats=mens-jeans,shirts&product_tags=fall,classic-style&attr_color=charcoal,brown&attr_size=large,x-small&cnep=0';
var query = s.split('?')[1],
pairs = query.split('&'),
allowed = ['product_cats', 'product_tags', 'attr_color', 'attr_size'],
results = [];
$.each(pairs, function(i, pair) {
var key_value = pair.split('='),
key = key_value[0],
value = key_value[1];
if (allowed.indexOf(key) > -1) {
results.push(value);
}
});
console.log(results.join(','));
($.each is from jQuery, but can easily be replaced if jQuery is not around)
I have a list of url extensions that i want to string replace using regex so that both upper and lower case is captured like this:
str = str.replace(/\.net/i,"")
.replace(/\.com/i,"")
.replace(/\.org/i,"")
.replace(/\.net/i,"")
.replace(/\.int/i,"")
.replace(/\.edu/i,"")
.replace(/\.gov/i,"")
.replace(/\.mil/i,"")
.replace(/\.arpa/i,"")
.replace(/\.ac/i,"")
.replace(/\.ad/i,"")
.replace(/\.ae/i,"")
.replace(/\.af/i,"");
When i try to clean this up using arrays and loops like so, i get an error. Can anyone help me with syntax please
var arr = [ "net","com","org","net","int","edu","gov","mil","arpa","ac","ad","ae"];
str = str.replace(/\.com/i,"")
for(ii==0;ii<=arr.length;ii++){
.replace('/\.'+arr[ii]+'/i',"") // i know this '/\.' and '/i' should not be a string but how would i write it?
}
.replace(/\.af/i,"");
You can just do like this instead of running replace multiple times in a loop:
str = str.replace(/\.(com|net|org|gov|edu|ad|ae|ac|int)/gi, '');
You need to create a RegExp object. You also need to apply .replace to the string, and assign the result.
for (ii = 0; ii < arr.length; ii++) {
str = str.replace(new Regexp('\\.' + arr[ii], 'i'));
}
I have a string, where I need to parse it as a float, but first I need to replace it, if it is not a number (an integer or a float), so I am trying to create an regular expression to do it
My tries results in NaN
One of my best tries is
var $replace = $text.replace(/^[^d.]*/, '');
var $float = parseFloat($replace);
Can anybody tell me, what I am doing wrong?
If you really want to replace everything thats not a digit, then try this:
var $replace = $text.replace(/[^\d.]/g, '');
var $float = parseFloat($replace);
This will replace a string of "123a3d2" with a string of "12332".
It looks like you want to strip "non-numeric" characters from the beginning of the string before converting it to float. A naive approach would be:
var s = input.replace(/^[^\d.]+/, '');
var n = parseFloat(s);
This works for inputs like "foo123" but will fail on "foo.bar.123". To parse this we need a more sophisticated regexp:
var s = input.replace(/^(.(?!\d)|\D)+/, '');
var n = parseFloat(s);
Another method is to strip the input char by char until we find a valid float:
function findValidFloat(str) {
for (var i = 0; i < str.length; i++) {
var f = parseFloat(str.substr(i))
if (!isNaN(f))
return f;
}
return NaN;
}
if (! isNaN($text))
$float = parseFloat($text);
else
$float = 0; // or whatever