How do you get the length of a string? - javascript

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;

Related

How to Extract only numeric value only from the URL javascript or jquery

Have URL'S which has a numeric value in it. Need to extract that numeric value. But the numeric value position is not constant in the URL. Need a generic way how to extract. Can't use the split method because the position of the value is not constant.
For example:
1. https:// www.example.com/A/1234567/B/D?index.html
2. http://www.example.com/A?index.html/pd=1234567
3. http://www.example.com/A/B/C/1234567?index.html
So the above three URL'S has a numeric value whose position is not constant.
Can you please provide a generic method where I can get the expected output like "1234567".
Use a basic regular expression:
"http://www.example.com/A?index.html/pd=1234567".match( /\d+/ );
This returns the first series of numbers in the string. In the above case, we get the following:
[ "1234567" ]
Here's a fiddle.
$(this).text().match(/\d+/)[0]
Note that this implies that there are no other numeral sequences in the url! No where!
Another working one :)
var str ="https:// www.example.com/A/1234567/B/D?index.html";
var numArray = [];
for (var i = 0, len = str.length; i < len; i++) {
var character = str[i];
if(isNumeric(character)){
numArray.push(character);
}
}
console.log(numArray);
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n)
}
Check out the FIDDLE LINK
Adding to #Jonathan, if you want to match all the numeric values then you can use htmlContent.match(/\d+/g)
To scrap a number from the URL is like scraping a number from any string, as long as your link follows the general rule of having the same format every time : meaning just one number. Maybe you will encounter a problem with the port.
This being said you would need to extract the URL : window.location.pathname, so you will get only what is after the "http://example.com:8080" in the URL.
Then parse the URL string with a regular expression : urlString.match('[\\d]+');
For example :
function getUrlId(){
var path = window.location.pathname;
var result = path.match('[\\d]+');
return result[0];
};

Jquery data-target as string possible?

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

String manipulation in javascript (remove leading zero & specific character)

var patt = path.match(/P[0-9][0-9][0-9]/);
patt = patt.substr(1); //Remove P
while(patt.charAt(0) === '0') { //Remove 0
patt = patt.substr(1);
}
alert(patt);
patt is fixed to this format:
eg. P001 to P999
What I would like to do is very basic, just remove P and the leading 0 (if any). However, the code above is not working. Thanks for helping
Please use it like this:
var str = patt.join('');
str = str.replace(/P0*/, '');
If the input to this function is guaranteed to be valid (i.e. of the form P001...P999), then you can simply use the following to extract the integer:
parseInt(path.substr(1), 10)
This seems the perfect use case for the global parseInt function.
parseInt(patt.substr(1), 10);
It takes as input the string you want to parse, and the base.
The base is optional, but most people suggest to always explicitly set the base to avoid surprises which may happen in some edge case.
It stops to parse the string as soon as it encounters a not numerical value (blank spaces excluded).
For this reason in the snippet above we're a passing the input string stripped of the first character, that as you've mentioned, is the letter "P".
Also, ES2015 introduced a parseInt function, as static method on the Number constructor.
Just a single line and you get what you want
var path = "P001"; //your code from P001 - P999
solution to remove P and the leading "0" .
parseInt(path.substr(1), 10);
Thanks and Regards

How can I parse a value out of a string with javascript?

I a string name content that has inside the text "data-RowKey=xxx". I am trying to get out xxx so I tried the following:
var val = content.substring(12 + content.indexOf("data-RowKey="), 3);
This does not work at all. rather than just get three characters I get a very long string. Can anyone see what I am doing wrong
You're using wrong tool. When you want to capture a data matching some pattern, you should use regular expressions. If your value is exactly three symbols, correct expression would be /data-RowKey=(...)/ with . standing for any symbol and () specifying part to capture.
.substring() [MDN] takes two indexes, .substr() [MDN] takes an index and the length. Try:
var val = content.substr(12 + content.indexOf("data-RowKey="), 3);
If "data-RowKey=xxx" is the whole string, there are various other ways to get xxx:
var val = content.replace('data-RowKey=', '');
var val = content.split('=')[1]; // assuming `=` does not appear in xxx
This works:
var value = content.match(/data-RowKey=(.*)/)[1];
Live DEMO
If there could be values after the xxx, use this:
"data-RowKey=123abc".match(/data-RowKey=(.{3}).*/)[1] // 123
If your rowkey is numeric, this might be best since you get the number as an integer and wouldn't need to convert later:
var val = parseInt( content.split("data-RowKey=")[1] );
If always the three characters and/or no need to convert:
var val = content.split("data-RowKey=")[1].substring(0,3);

Splitting string in javascript

How can I split the following string?
var str = "test":"abc","test1":"hello,hi","test2":"hello,hi,there";
If I use str.split(",") then I won't be able to get strings which contain commas.
Whats the best way to split the above string?
I assume it's actually:
var str = '"test":"abc","test1":"hello,hi","test2":"hello,hi,there"';
because otherwise it wouldn't even be valid JavaScript.
If I had a string like this I would parse it as an incomplete JSON which it seems to be:
var obj = JSON.parse('{'+str+'}');
and then use is as a plain object:
alert(obj.test1); // says: hello,hi
See DEMO
Update 1: Looking at other answers I wonder whether it's only me who sees it as invalid JavaScript?
Update 2: Also, is it only me who sees it as a JSON without curly braces?
Though not clear with your input. Here is what I can suggest.
str.split('","');
and then append the double quotes to each string
str.split('","'); Difficult to say given the formatting
if Zed is right though you can do this (assuming the opening and closing {)
str = eval(str);
var test = str.test; // Returns abc
var test1 = str.test1; // returns hello,hi
//etc
That's a general problem in all languages: if the items you need contain the delimiter, it gets complicated.
The simplest way would be to make sure the delimiter is unique. If you can't do that, you will probably have to iterate over the quoted Strings manually, something like this:
var arr = [];
var result = text.match(/"([^"]*"/g);
for (i in result) {
arr.push(i);
}
Iterate once over the string and replace commas(,) following a (") and followed by a (") with a (%) or something not likely to find in your little strings. Then split by (%) or whatever you chose.

Categories

Resources