Jquery data-target as string possible? - javascript

I have a data-attribute with a unique name and a number at the end.
data-target="foo-bar-n"
where n is the unique number.
I want to be able to get that number but it isn't working.
I call:
.data("target")
on the object I want the target from and It returns fine, but when I use a regex search on the results, I get a completely different number, which I suspect is because returned data is an object with other data. What I need to know is how to get that number out, or how to convert the data-attribute into a string. (I've tried toString, and that doesn't work.)
Here is my code:
var selection= window.getSelection().getRangeAt(0);
var showSelection = $(selection.commonAncestorContainer.parentNode.parentNode)
.data('target');
console.log(showSelection);
console.log(showSelection.search(/\d+/));
The console logs
#comment_for_paragraph_17
23
The program is meant to let a user select something on the page and highlight it.

If you are using jQuery 1.4.3 or later you can use
.data("target");
otherwise you must use
.attr("data-target");
But your requirement appears to be extracting a number from a formatted string parameter?
HTML:
<div id="foo" data-target="foo-bar-5"></div>
jQuery:
var num = $('#foo').data('target').split('-')[2];
Or regex:
var num = $('#foo').data('target').match(/\d+/);
Or if your requirement is specifically capture the last number in the string (eg: foo-bar-55-23 would result in '23')
var num = $('#foo').data('target').split('-').slice(-1);
// regex
var num = $('#foo').data('target').match(/\d+$/);
See fiddle

I suspect is because returned data is an object with other data.
That doesn't make any sense at all. The reason you are not getting the number in the string is because .search returns the index of the match. Use .match or .exec instead:
showSelection.match(/\d+/)[0];
/*or*/
/\d+/.exec(showSelection)[0];

Try:
.data('target').split('-').slice(-1)[0];
.split will split your string into an array with each array element being a word
.slice(-1) will return an array consisting of the last element of your array
[0] accesses the array element

Related

get the matched data into array in javascript without using any loop

Problem background -- I want to get the nth root of the number where user can enter expression like "the nth root of x'.I have written a function nthroot(x,n) which return proper expected output.My problem is to extract the value of x and n from expression.
I want to extract some matched pattern and store it to a an array for further processing so that in next step i will pop two elements from array and replace the result in repression.But I am unable to get all the values into an array without using loop.
A perl equivalent of my code will be like below.
$str = "the 2th root of 4+678+the 4th root of -10000x90";
#arr = $str =~ /the ([-+]?\d+)th\s?root\s?of\s?([-+]?\d+)/g;
print "#arr";
I want the javascript equivalent of the above code.
or
any one line expression like below.
expr = expr.replace(/the\s?([+-]\d+)th\s?root\s?of([+-]\d+)/g,nthroot(\\$2,\\$1));
Please help me for the same.
The .replace() method that you are currently using is, as its name implies, used to do a string replacement, not to return the individual matches. It would make more sense to use the .match() method instead, but you can (mis)use .replace() if you use a callback function:
var result = expr.replace(/the\s?([+-]\d+)th\s?root\s?of([+-]\d+)/,function(m,m1,m2){
return nthroot(+m2, +m1);
});
Note that the arguments in the callback will be strings, so I'm converting them to numbers with the unary plus operator when passing them to your nthroot() function.
var regex=/the ([-+]?\d+)th\s?root\s?of\s?([-+]?\d+)/g;
expr=expr.replace(regex, replaceCallback);
var replaceCallback = function(match,p1,p2,offset, s) {
return nthroot(p2,p1);
//p1 and p2 are similar to $1 $2
}

What does split function look like?

I came across this statement :
userName = document.cookie.split("=")[1];
after reading about split statement here at w3schools. which says that syntax of split is
string.split(separator, limit). Then what does the square bracket after first parens. mean ?
If this is true what does split function look like ?
String.split(separator, limit) returns an array. In Javascript, you can access array values by index using the square brackets. Arrays are zero-based, 0 is the first element, 1 the second and so on.
The equivalent of your code would be:
var arr = document.cookie.split("=");
userName = arr[1];
This separates the document.cookie by the equal-sign (=) and takes the second element (index 1) from it. document.cookie is a special property (datatype: String) of the document object which contains all cookies of a webpage, separated by the ; character. E.g. if document.cookie contains name=Adam, the array arr will contain the values name and Adam. The second one is stored in userName.
Note that if the cookie contains multiple values, or if the value contains multiple equal-signs, it won't work. Consider the next cases:
document.cookie contains name=Adam; home=Nowhere. Using the above code, this would make userName contain Adam; home because the string is separated by the equal-sign, and then the second value is taken.
document.cookie contains home=Nowhere; name=Adam. This would result in userName containing Nowhere; name
document.cookie contains name=Adam=cool. In this case, userName would be Adam and not Adam=cool.
Also, w3schools is not that reliable. Use more authorative sources like the Mozilla Developer Network:
document.cookie
String.split
Array
The split function returns an array of strings split by the given separator. With the square bracket you are accessing the nth element of that (returned) array.
If you are familiar with Java, its the same behavior as the String.split() method there.
It gets the second index of the resulting array
Same as:
var split = document.cookie.split("=");
var userName = split[1];
split returns an array of strings. So square brackets mean get second string from the returned array.
The square bracket in the code you supplied is accessing the second element of the array returned by split(). The function itself returns an array. That code would be the same as:
var temp = document.cookie.split("=");
userName = temp[1];
Split would return an array e.g. [1, 2, 3]. If you supply the square bracket after it, it will return the specified key in the brackets, in this case userName would be 2
You shouldn't be using w3schools, but...
In JavaScript, function parameters are optional and it is possible to supply fewer parameters than the function expects. The extra parameters in the function are then undefined. Some functions are programmed to deal with that possibility and string.split is one of them.
The other part has to do with the fact that split returns an array. Arrays can then be indexed using the square bracket notation, hence the [1] after the function call.

Regex to extract substring, returning 2 results for some reason

I need to do a lot of regex things in javascript but am having some issues with the syntax and I can't seem to find a definitive resource on this.. for some reason when I do:
var tesst = "afskfsd33j"
var test = tesst.match(/a(.*)j/);
alert (test)
it shows
"afskfsd33j, fskfsd33"
I'm not sure why its giving this output of original and the matched string, I am wondering how I can get it to just give the match (essentially extracting the part I want from the original string)
Thanks for any advice
match returns an array.
The default string representation of an array in JavaScript is the elements of the array separated by commas. In this case the desired result is in the second element of the array:
var tesst = "afskfsd33j"
var test = tesst.match(/a(.*)j/);
alert (test[1]);
Each group defined by parenthesis () is captured during processing and each captured group content is pushed into result array in same order as groups within pattern starts. See more on http://www.regular-expressions.info/brackets.html and http://www.regular-expressions.info/refcapture.html (choose right language to see supported features)
var source = "afskfsd33j"
var result = source.match(/a(.*)j/);
result: ["afskfsd33j", "fskfsd33"]
The reason why you received this exact result is following:
First value in array is the first found string which confirms the entire pattern. So it should definitely start with "a" followed by any number of any characters and ends with first "j" char after starting "a".
Second value in array is captured group defined by parenthesis. In your case group contain entire pattern match without content defined outside parenthesis, so exactly "fskfsd33".
If you want to get rid of second value in array you may define pattern like this:
/a(?:.*)j/
where "?:" means that group of chars which match the content in parenthesis will not be part of resulting array.
Other options might be in this simple case to write pattern without any group because it is not necessary to use group at all:
/a.*j/
If you want to just check whether source text matches the pattern and does not care about which text it found than you may try:
var result = /a.*j/.test(source);
The result should return then only true|false values. For more info see http://www.javascriptkit.com/javatutors/re3.shtml
I think your problem is that the match method is returning an array. The 0th item in the array is the original string, the 1st thru nth items correspond to the 1st through nth matched parenthesised items. Your "alert()" call is showing the entire array.
Just get rid of the parenthesis and that will give you an array with one element and:
Change this line
var test = tesst.match(/a(.*)j/);
To this
var test = tesst.match(/a.*j/);
If you add parenthesis the match() function will find two match for you one for whole expression and one for the expression inside the parenthesis
Also according to developer.mozilla.org docs :
If you only want the first match found, you might want to use
RegExp.exec() instead.
You can use the below code:
RegExp(/a.*j/).exec("afskfsd33j")
I've just had the same problem.
You only get the text twice in your result if you include a match group (in brackets) and the 'g' (global) modifier.
The first item always is the first result, normally OK when using match(reg) on a short string, however when using a construct like:
while ((result = reg.exec(string)) !== null){
console.log(result);
}
the results are a little different.
Try the following code:
var regEx = new RegExp('([0-9]+ (cat|fish))','g'), sampleString="1 cat and 2 fish";
var result = sample_string.match(regEx);
console.log(JSON.stringify(result));
// ["1 cat","2 fish"]
var reg = new RegExp('[0-9]+ (cat|fish)','g'), sampleString="1 cat and 2 fish";
while ((result = reg.exec(sampleString)) !== null) {
console.dir(JSON.stringify(result))
};
// '["1 cat","cat"]'
// '["2 fish","fish"]'
var reg = new RegExp('([0-9]+ (cat|fish))','g'), sampleString="1 cat and 2 fish";
while ((result = reg.exec(sampleString)) !== null){
console.dir(JSON.stringify(result))
};
// '["1 cat","1 cat","cat"]'
// '["2 fish","2 fish","fish"]'
(tested on recent V8 - Chrome, Node.js)
The best answer is currently a comment which I can't upvote, so credit to #Mic.

How do you get the length of a string?

How do you get the length of a string in jQuery?
You don't need jquery, just use yourstring.length. See reference here and also here.
Update:
To support unicode strings, length need to be computed as following:
[..."𠮷"].length
or create an auxiliary function
function uniLen(s) {
return [...s].length
}
The easiest way:
$('#selector').val().length
jQuery is a JavaScript library.
You don't need to use jQuery to get the length of a string because it is a basic JavaScript string object property.
somestring.length;
A somewhat important distinction is if the element is an input or not. If an input you can use:
$('#selector').val().length;
otherwise if the element is a different html element like a paragraph or list item div etc, you must use
$('#selector').text().length;
HTML
<div class="selector">Text mates</div>
SCRIPT
alert(jQuery('.selector').text().length);
RESULT
10
You don't need to use jquery.
var myString = 'abc';
var n = myString.length;
n will be 3.
It's not jquery you need, it's JS:
alert(str.length);
same way you do it in javascript:
"something".length
In some cases String.length might return a value which is different from the actual number of characters visible on the screen (e.g. some emojis are encoded by 2 UTF-16 units):
MDN says:
This property returns the number of code units in the string. UTF-16, the string format used by JavaScript, uses a single 16-bit code unit to represent the most common characters, but needs to use two code units for less commonly-used characters, so it's possible for the value returned by length to not match the actual number of characters in the string.
In Unicode separate visible characters are called graphemes. In case you need to account for this case, you'll need some lib that can split the string into graphemes, such as this: https://www.npmjs.com/package/grapheme-splitter
In jQuery :
var len = jQuery('.selector').val().length; //or
( var len = $('.selector').val().length;) //- If Element is Text Box
OR
var len = jQuery('.selector').html().length; //or
( var len = $('.selector').html().length; ) //- If Element is not Input Text Box
In JS :
var len = str.length;

Help with regex in javascript

I have this sample text, which is retrieved from the class name on an html element:
rich-message err-test1 erroractive
rich-message err-test2 erroractive
rich-message erroractive err-test1
err-test2 rich-message erroractive
I am trying to match the "test1"/"test2" data in each of these examples. I am currently using the following regex, which matches the "err-test1" type of word. I can't figure out how to limit it to just the data after the hyphen(-).
/err-(\S*)/ig
Head hurts from banging against this wall.
From what I am reading, your code already works.
Regex.exec() returns an array of results on success.
The first element in the array (index 0) returns the entire string, after which all () enclosed elements are pushed into this array.
var string = 'rich-message err-test1 erroractive';
var regex = new RegExp('err-(\S*)', 'ig');
var result = regex.exec(string);
alert(result[0]) --> returns err-test1
alert(result[1]) --> returns test1
You could try 'err-([^ \n\r]*)' - but are you sure that it is the regex that is the problem? Are you using the whole result, not just the first capture?
The stuff after the - should be in the results array. The first item is all the matching text (e.g. "err-test1") and the next items are the matches from the capture parentheses (e.g. "test1").
myregex = /err-(\S*)/ig;
mymatch = myregex.exec("data with matches in it");
testnum = mymatch[1];
Here's a reference site.

Categories

Resources