How does split and join work in JavaScript? - javascript

But still dont understand : as in input box initially there is no data , however when the user starts typing the functions starts invoking the method in it , however the first line will [ $(this).val().split("-").join(""); ] will then look for the hyphen character to split into ... but as if the data typed by the user dosent contains any hyphens so what has to be replaced...??? like you explained above e.g. split("-") on "a-b-c" will give ["a","b","c"] ....this data already contains the hyphen character and which gets replaced with the character that we specify in brackets. Again at the other hand i dont understand this too : foo = foo.match(new RegExp('.{1,4}', 'g')).join("-"); , why there is single quotes in the RegExp, and what for the 1,4 stands for ..??? as far a i know that it must be meant for minimum 1 and maximum 4 charachters..? could you please help me understanding this..??? Appreciate your help

The function calls are evaluated from left to right. First val(), then split("-")and then join("").
What this does, is that it reads the value and since it seems to be a credit card number, the value will be something like 1234-5678-9012-3456.
The next thing is split the numbers at the hyphens with split("-"). This will result in a kind of list ['1234', '5678', '9012', '3456'].
This list is then joined using "" (Nothing actually) resulting in 1234567890123456, the number without the hyphens.
The same thing could be achieved with
$(this).val().replace(/-/g, "")
using Regular Expressions.
Hope this clarifies stuff!

$(this).val()
Gets the value of the element:
.split("-")
Build an array of strings that splits on '-' (hyphen). Basically, when you find '-' in the string, add it to i.e. 'foo-bar' becomes ['foo', 'bar'].
.join("");
Take the array and join each element back together with an empty string i.e. ['foo', 'bar'] becomes 'foobar'.

Split and join in one line
const result = "7.83".split('.').reduce((first, second) => `${first}' ${second}"`)
console.log(result)
7' 83"

Related

Why JS Regexp.exec returns an array with more elements than expected?

I'm attempting to regex match various duration strings (e.g. 1d10h, 30m, 90s, etc.) and have come up with a regex string to split the string into pieces, but it seems that I'm getting two undefined results at the ends that shouldn't be there. I imagine it has to do with the greedy matching via the ? groupings, but I'm not sure how to fix it.
My code looks like this:
const regex = /^(\d+?[d])?(\d+?[h])?(\d+[m])?(\d+[s])?$/gmi
const results = regex.exec('1d10h')
and the results I get look like so:
[
"1d10h",
"1d",
"10h",
undefined,
undefined,
]
I was only expecting the first three results (and in fact, I only really want 1d and 10h) but the two remaining undefined results keep popping up.
You have 4 groups in the regular expression - each enclosed with braces ( ... ) and enumerated naturally - the earlier opening brace appear in the expression the lower order index a group has.
And, of course, the whole match that could be named a "zero" group.
So, result of regex.exec('1d10h') contains 5 items:
results[0] - the whole expression match
results[i] - match of each group, i in {1,2,3,4}
Since in this case each group is optional (followed by ?) - it is allowed to have undefined in place of any unmatched group.
It is easy to see that if you remove a ? symbol after an unmatched group, the whole expression will fail to match and hence regex.exec('1d10h') will return null.
To get rid of undefined elements just filter them out:
const result = regex.exec('1d10h').filter(x => x);

Slice method is not consistent

I've created a function to parse a string of text and look for a combination of key words. The key words and their indexes are then captured and used later on to reassemble the full string from first to last keyword, including all words in between. I'm using array.slice to pull the string from the array however it's inconsistent and sometimes requires incrementing\decrementing the second value in order to get the exact match. I've created a jsfiddle http://jsfiddle.net/jkeohan/g7vdgg1a/4/ to demo it.
line 50 and 64 the ones where slice is being used and in one instance index+1 is used and the other index-1. Both produce the same results, most of the time.
var phrase = (datafull.slice( (comparearray[0].index-1),
(comparearray[comparearray.length-2].index+1) ) ).join(" ")
matchingString = (datafull.slice( (comparearray[0].index-1),
(comparearray[comparearray.length-3].index-1) ) ).join(" ")
Any ideas?

Matching and returning a regex between two values

I am trying to get the values from a string using regex, the value is that of the text between tt=" and "&
So, for example, "tt="Value"&" I would only want to get the word "Value" out of this.
So far I have this: /tt=.*&/ which gives me "tt=Value"&, Then, to get the value I am thinking to split the match on = and remove the 2 characters from the end. I feel though, that this would be an awful way to do this and would like to see if it could be done in the regex?
You're on the right track for matching the entire context inside of the string, but you want to use a capturing group to match/capture the value between the quotes instead of splitting on = and having to remove the two quote chars.
var r = 'tt="Value"&'.match(/tt="([^"]*)"/)[1];
if (r)
console.log(r); //=> "Value"
I know this isn't really the answer you are looking for since it doesn't involve regex but it's the way I usually do it.
strvariable = strvariable.Remove(0,strvariable.IndexOf("=") + 2);
strvariable = strvariable.Remove(strvariable.IndexOf("\""), strvariable.Length - strvariable.IndexOf("\""));
this would give you the result you were looking for which is Value in this instance.

Extract Fractional Number From String

I have a string that looks something like this
Hey this is my 1.20 string
I'm trying to just extract 1.20 from it.
What's the best way to do this?
I've tried something like this, but I get the value of 1.20,20 rather than just 1.20
var query = $(".query_time").html();
var matches = query.match(/\d.(\d+)/);
The result of the match function is an array, not a string. So simply take
var nb = query.match(/\d.(\d+)/)[0];
BTW, you should also escape the dot if you want to have more precise match :
var nb = query.match(/\d\.(\d+)/)[0];
or this if you want to accept commas (depends on the language) :
var nb = query.match(/\d[\.,](\d+)/)[0];
But the exact regex will be based on your exact needs, of course and to match any number (scientific notation ?) I'd suggest to have a look at more complex regex.
The value of matches is actually [ "1.20", "20" ] (which is an array). If you print it, it will get converted to a string, hence the 1.20,20.
String.match returns null or an array of matches where the first index is the fully matched part and then whichever parts you wanted. So the value you want is matches[0].
Try the following
var nb = query.match(/\d\.\d+/)[0]; // "1.20"
You need to escape . because that stands for any character.
Remove the capture group (\d+) and the second match is not returned
Add [0] index to retrieve the match

Javascript: How can I search and replace multiple items with matched groups?

Say I have a string like
"item:(one|two|three), item2:(x|y)"
Is there a single regex that could "factor" it into
"item:one, item:two, item:three, item2:x, item2:y"
Or must I resort to splitting and looping?
If I must split it up then how do I even turn
"item:(one|two|three)"
into
"item:one, item:two, item:three"
if the amount of things between the parentheses is variable? Are regexes useless for such a problem?
You could do it with a callback function:
str = str.replace(/(\w+):\(([^)]*)\)/gi, function(match,item,values)
{return item + ':' + values.split("|").join(', '+item+':')}
);
For every item, the first parentheses in the regex capture the item's name (i.e item) and the second set of (unescaped) parentheses capture the string of all values (i.e one|two|three). The latter are then split at | and joined together with , itemname: and then there is another item name appended to the beginning of the result.
This is probably the easiest way to combine regexes to find your data and split and join to build your new regex. The problem why it is not easier is, that you cannot capture an arbitrary number of consecutive values (one|two|three) in different capturing groups. You would only get the last one, if you tried to capture them individually.

Categories

Resources