I am trying to write a javascript , And want to count digits of a var str,
in the code below var str is 6 digits (012345), but when i run this code it is showing answer 4. i tried to search on google but answer not found;
how to get correct answer and fix it ?
my code
var str = 012345;
var x = String(str);
var n = x.length;
document.getElementById("demo").innerHTML = "var str is[" + n + "] Digits";
Initialize you phone number as string using quotes.
var str = '0123213'
And use length property to get its length
If you were to actually have a mixed letter/number string from which you wanted to get the number of digits you could use a regex. match creates an array of all the matches in the string - in this case \d, a digit (g says to check the whole of the string, not give up the search when the first digit has been found.) You can then check the length of the returned array.
'01xx2s3eg345'.match(/\d/g).length; // 7
try replacing the code with:
var str = "012345";
var n = str.length;
document.getElementById("demo").innerHTML = "var str is[" + n + "] Digits";
Related
I have a string that I would like to break down into an array.
Each index needs to have a max letter, say 15 characters. Each point needs to be at a words end, with no overlap of the maximum characters (IE would stop at 28 chars before heading into next word).
I've been able to do similar things using regex in the past, but I'm trying to make this work with an online platform that does not like regex.
Example string:
Hi this is a sample string that I would like to break down into an array!
Desired result # 15 char max:
Hi this is a
sample string
that I would
like to break
down into an
array!
Considering there's no word bigger then max limit
function splitString (n,str){
let arr = str?.split(' ');
let result=[]
let subStr=arr[0]
for(let i = 1; i < arr.length; i++){
let word = arr[i]
if(subStr.length + word.length + 1 <= n){
subStr = subStr + ' ' + word
}
else{
result.push(subStr);
subStr = word
}
}
if(subStr.length){result.push(subStr)}
return result
}
console.log(splitString(15,'Hi this is a sample string that I would like to break down into an array!'))
I'm trying to make a Regex in JavaScript to match each not escaped specific characters.
Here I'm looking for all the ' characters. They can be at the beginning or the end of the string, and consecutive.
E.g.:
'abc''abc\'abc
I should get 3 matchs: the 1st, 5 and 6th character. But not 11th which escaped.
You'll have to account for cases like \\' which should match, and \\\' which shouldn't. but you don't have lookbehinds in JS, let alone variable-length lookbehinds, so you'll have to use something else.
Use the following regex:
\\.|(')
This will match both all escaped characters and the ' characters you're looking for, but the quotes will be in a capture group.
Look at this demo. The matches you're interested in are in green, the ones to ignore are in blue.
Then, in JS, ignore each match object m where !m[1].
Example:
var input = "'abc''abc\\'abc \\\\' abc";
var re = /\\.|(')/g;
var m;
var positions = [];
while (m = re.exec(input)) {
if (m[1])
positions.push(m.index);
}
var pos = [];
for (var i = 0; i < input.length; ++i) {
pos.push(positions.indexOf(i) >= 0 ? "^" : " ");
}
document.getElementById("output").innerText = input + "\n" + pos.join("");
<pre id="output"></pre>
You can use:
var s = "'abc''abc\\'abc";
var cnt=0;
s.replace(/\\?'/g, function($0) { if ($0[0] != '\\') cnt++; return $0;});
console.log(cnt);
//=> 3
I have a string :
var str = "u12345a45";//position is 7 here
now i want the position of 'a'(alphabet) in that string
similarly i have few more string like this:
var str1 = "u1234567a45";//position is 9 here
var str2 = "u12345b4";//position of b is 7 here
var str3 = "u123c";//position of c is 5 here
var str4 = "u3d45";//position of d is 2 here
Now what i thought of doing is , just searching the string from last and know the occurrence of any alphabet in that strings for once.
Note:It might be any alphabet in a string like this:
var str5 = "u2233b45";//position of b is 6 here
var str6 = "u22333f45";//position of f is 7 here
any help will be appreciated .
thanks.
As simple as
str.indexOf('a') + 1
for an arbitrary non-digit character it could be
str.match(/\D/).index + 1
for the last non-digit character followed by 0..inf digit characters:
str.match(/\D\d*$/).index + 1
just use indexOf method.
var str1 = "1234567a45";
alert(str1.indexOf("a") + 1); // alerts 8
You can use JavaScript's indexOf method.
var pos1 = str1.indexOf('a'); // will equal 7
var pos2 = str2.indexOf('a'); // will equal 5
var pos3 = str3.indexOf('a'); // will equal 3
var pos4 = str4.indexOf('a'); // will equal 0
Here's a small Codesnippet that should solve your Problem.
var str1= "12345t45";
var str1Length = str1.length;
for(var a=0; a<str1Length ;a++){
if(isNaN(str1.substring(a,a+1))){
alert(str1.substring(a,a+1)+' at Position : '+(a+1));
}
}
I loope through the string and check if the actual position is a letter or a number. If it's a Letter i write him into the alert. In this Case the Alert says : 't' at Position : 6
Regards, Miriam
I have a string, 15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt, I'd like to make it looks like 15.Prototypal...-Slider.txt
The length of the text is 56, how can I keep the first 12 letters and 10 last letters (incuding punctuation marks) and replace the others to ...
I don't really know how to commence the code, I made something like
var str="15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt";
str.split("// ",1);
although this gives me what I need, how do I have the results base on letters not words.
You can use str.slice().
function middleEllipsis(str, a, b) {
if (str.length > a + b)
return str.slice(0, a) + '...' + str.slice(-b);
else
return str;
}
middleEllipsis("15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt", 12, 10);
// "15.Prototypa...Slider.txt"
middleEllipsis("mpchc64.mov", 12, 10);
// "mpchc64.mov"
This function will do what you ask for:
function fixString(str) {
var LEN_PREFIX = 12;
var LEN_SUFFIX = 10;
if (str.length < LEN_PREFIX + LEN_SUFFIX) { return str; }
return str.substr(0, LEN_PREFIX) + '...' + str.substr(str.length - LEN_SUFFIX - 1);
}
You can adjust the LEN_PREFIX and LEN_SUFFIX as needed, but I've the values you specified in your post. You could also make the function more generic by making the prefix and suffix length input arguments to your function:
function fixString(str, prefixLength, suffixLength) {
if (str.length < prefixLength + suffixLength) { return str; }
return str.substr(0, prefixLength) + '...' + str.substr(str.length - suffixLength - 1);
}
I'd like to make it looks like 15.Prototypal...-Slider.txt
LIVE DEMO
No matter how long are the suffixed and prefixed texts, this will get the desired:
var str = "15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt",
sp = str.split('-'),
newStr = str;
if(sp.length>1) newStr = sp[0]+'...-'+ sp.pop() ;
alert( newStr ); //15.Prototypal...-Slider.txt
Splitting the string at - and using .pop() method to retrieve the last Array value from the splitted String.
Instead of splitting the string at some defined positions it'll also handle strings like:
11.jQuery-infinite-loop-a-Gallery.txt returning: 11.jQuery...-Gallery.txt
Here's another option. Note that this keeps the first 13 characters and last 11 because that's what you gave in your example.:
var shortenedStr = str.substr(0, 13) + '...' + str.substring(str.length - 11);
You could use the javascript substring command to find out what you want.
If you string is always 56 characters you could do something like this:
var str="15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt";
var newstr = str.substring(0,11) + "..." + str.substring(45,55)
if your string varies in length I would highly recommend finding the length of the string first, and then doing the substring.
have a look at: http://www.w3schools.com/jsref/jsref_substring.asp
This question already has answers here:
Regular Expression for accurate word-count using JavaScript
(8 answers)
Closed 8 years ago.
I was trying to count the total number of words in a sentence. I have used the following code in Javascript.
function countWords(){
s = document.getElementById("inputString").value;
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");
alert(s.split(' ').length);
}
So if I gave following inputs,
"Hello world" -> alerts 2 //fine
"Hello world<space>" -> alerts 3 // supposed to alert 2
"Hello world world" -> alerts 3 //fine
Where I went wrong?
here you will find all you need.
http://jsfiddle.net/deepumohanp/jZeKu/
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex, '').length;
$('#wordCount').html(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);
try this one please:
var word = "str";
function countWords(word) {
var s = word.length;
if (s == "") {
alert('count is 0')
}
else {
s = s.replace (/\r\n?|\n/g, ' ')
.replace (/ {2,}/g, ' ')
.replace (/^ /, '')
.replace (/ $/, '');
var q = s.split (' ');
alert ('total count is: ' + q.length);
}
}
Split will split event if there is your separator (in your case ' ') at the end of the string, resulting in creating a last [] item in the list.
What you can do is use the split(" ") function (including the space inside quotation) to convert the string to an array consisting of only the words. Then you can get the length of the array by using array.length which would essentially be the number of words in your string.