I keep getting a result of 0 whenever I type in a search term. I'm trying to find the number of times that a pattern occurs in string. So for example searching for at would return 3. Any advice on where I'm going wrng?
string =
[
"cat math path"
]
var pattern = prompt('Please enter a search term:');
function check(string,pattern)
{
if(pattern)
{
if(pattern.indexOf(string) == -1)
{
return 0;
}
return count(pattern.substring(pattern.indexOf(string)+string.length), string)+1;
}
else
{
return("Nothing entered!");
}
}
alert(check(string,pattern));
if(pattern.indexOf(string) == -1)
should be
if(string.indexOf(pattern) == -1)
I think you inverted the use of pattern and string. See the documentation of indexOf. Also you can easily count occurrences with split which breaks your string into an array:
count=string.split(pattern).length - 1;
Where string="cat math path"; (instead of an array)
Related
I'm working on a project that has an input field requiring user to enter only any of the following three options:
Number like 150
Number starting with one letter (which must be N, not case sensitive) like N150
Number ending with one letter (which must be N, not case sensitive) like 150N
Any other value like:
150x will return error message wrong input
x150 will return wrong input
1N50 will return wrong position
The correct way to do this is to make an array of valid numbers and then to check if the given text exists on your array.For example:
var validNumbers = [ 150, N150, 150N ];
if (validNumbers.indexOf(parseInt(num, 10)) >=0 ) {
//Match
}
You'll need an indexOf function for IE:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(needle) {
for(var i = 0; i < this.length; i++) {
if(this[i] === needle) {
return i;
}
}
return -1;
};
}
check this answer :
Regular expression to match a number range in JavaScript
and adjust to your needs, you can easily add the "N" at the end or at the beginning by adding regex part to make accept values like :
-N150
-150N
-130N
-N130
A non regexapproach (just to show why regex is useful):
function test(value){
//convert to array
value=value.split("");
//check the number
function isnumber(num){
return num.every(n=>"1234567890".includes(n));
}
//weve got three possibilities:
//150
if(isnumber(value)) return true;
//N150
var [n,...rest]=value;
if(n==="N" && isnumber(rest)) return true;
//150N
var n=value.pop();
return n==="N" && isnumber(value);
}
http://jsbin.com/kafivecedi/edit?console
I want to remove decimal from number in javascript:
Something like this:
12 => 12
12.00 => 1200
12.12 => 1212
12.12.12 => error: please enter valid number.
I can not use Math.round(number). Because, it'll give me different result. How can I achieve this? Thanks.
The simplest way to handle the first three examples is:
function removeDecimal(num) {
return parseInt(num.toString().replace(".", ""), 10);
}
This assumes that the argument is a number already, in which case your second and fourth examples are impossible.
If that's not the case, you'll need to count the number of dots in the string, using something like (trick taken from this question):
(str.match(/\./g) || []).length
Combining the two and throwing, you can:
function removeDecimal(num) {
if ((num.toString().match(/\./g) || []).length > 1) throw new Error("Too many periods!");
return parseInt(num.toString().replace(".", ""), 10);
}
This will work for most numbers, but may run into rounding errors for particularly large or precise values (for example, removeDecimal("1398080348.12341234") will return 139808034812341230).
If you know the input will always be a number and you want to get really tricky, you can also do something like:
function removeDecimal(num) {
var numStr = num.toString();
if (numStr.indexOf(".") === -1) return num;
return num * Math.pow(10, numStr.length - numStr.indexOf(".") - 1);
}
You can use the replace method to remove the first period in the string, then you can check if there is another period left:
str = str.replace('.', '');
if (str.indexOf('.') != -1) {
// invalid input
}
Demo:
function reformat(str) {
str = str.replace('.', '');
if (str.indexOf('.') != -1) {
return "invalid input";
}
return str;
}
// show in Stackoverflow snippet
function show(str) {
document.write(str + '<br>');
}
show(reformat("12"));
show(reformat("12.00"));
show(reformat("12.12"));
show(reformat("12.12.12"));
How about number = number.replace(".", ""); ?
I've done some research and can't seem to find a way to do this. I even tried using a for loop to loop through the string and tried using the functions isLetter() and charAt().
I have a string which is a street address for example:
var streetAddr = "45 Church St";
I need a way to loop through the string and find the first alphabetical letter in that string. I need to use that character somewhere else after this. For the above example I would need the function to return a value of C. What would be a nice way to do this?
Maybe one of the shortest solutions:
'45 Church St'.match(/[a-zA-Z]/).pop();
Since match will return null if there are no alphanumerical characters in a string, you may transform it to the following fool proof solution:
('45 Church St'.match(/[a-zA-Z]/) || []).pop();
Just check if the character is in the range A-Z or a-z
function firstChar(inputString) {
for (var i = 0; i < inputString.length; i += 1) {
if ((inputString.charAt(i) >= 'A' && inputString.charAt(i) <= 'Z') ||
(inputString.charAt(i) >= 'a' && inputString.charAt(i) <= 'z')) {
return inputString.charAt(i);
}
}
return "";
}
console.assert(firstChar("45 Church St") === "C");
console.assert(firstChar("12345") === "");
This can be done with match
"45 Church St".match(/[a-z]/i)[0]; // "C"
This code example should get the job done.
function numsNletters(alphanum) {
firstChar=alphanum.match(/[a-zA-Z]/).pop();
numsLetters=alphanum.split(firstChar);
numbers=numsLetters[0];
// prepending the letter we split on (found with regex at top)
letters=firstChar+numsLetters[1];
return numbers+'|'+letters;
}
numsNletters("123abc"); // returns "123|abc";
I have a string that starts with "TT" and ends with six digits(ex. "TT012345", "TT012000, TT329001). The string is always formatted like this and I need to check if the last digit in this string is of a certain value.
Say I have the string "TT032970". In this case I'd like to get a match on this string since the last digit is zero and the digit before that is a seven(I'm looking for 7).
The string "TT037000" should also be a match but "TT0329701" shouldn't(since it isn't all zeroes to the right of the seven(the "last" 7 in the string)).
I was thinking of using a set of nested if's using substr() to check all places of the string for zeroes and if it isn't a zero in position n, then I check if the digit I'm looking for exists in position n.
My code is repetitive and I'm all for being efficient.
This is what I got so far(that works but only checks the last place of the string and the second last place):
var lastDigit = [3, 7, 8], tda = document.querySelectorAll('td a'), i, j;
function checkArray(num) {
"use strict";
for (j = 0; j < lastDigit.length; j++) {
if (num === lastDigit[j]) {
return true;
}
}
}
for (i = 0; i < tda.length; i++) {
if ((parseInt(tda[i].textContent.substr(8, 1), 10) === 0 && checkArray(parseInt(tda[i].textContent.substr(7, 1), 10))) || checkArray(parseInt(tda[i].textContent.substr(8, 1), 10))) {
tda[i].style.background = "rgb(255, 144, 255)";
amountOfTickets.push(tda[i]);
}
}
I'm positive there's a great way of checking the string for trailing zeroes and check the first non-zero digit before the zeroes. However, I'm really bad with loops and I just can't figure out how.
I'm very keen on figuring it out myself but I need a head start. I'd rather take a detailed explanation on how to do it than just the "answer".
If anything else seem off I'd gladly listen to improvements.
Thanks in advance!
To get the first digit before the zeros at the end of a string, you may use a regular expression :
+string.match(/(\d)0*$/)[1]
Example 1 :
var string = "TT032970";
var digit = +string.match(/(\d)0*$/)[1];
console.log(digit); // logs 7
Example 2 :
console.log(["TT012345","TT012000","TT329001","TT032970"].map(function(string){
return +string.match(/(\d)0*$/)[1]
})); // logs [5, 2, 1, 7]
Demonstration
Obviously, from the other answers, a regular expression will be much simpler than your loops. Moreover, any nested loop solution will be difficult to work, as you don't know how many levels deep you have to look. (Is there one zero? Two? Five?)
This regex is quite simple:
/(\d)0+$/
If you do a match on that with your string, you should get either null if it doesn't match (e.g. "TT0329701") or a two-element array if it does (e.g. "TT037000" will return ["7000", "7"].)
That should be enough for your to build your own solution upon.
Best of luck.
The first thing I though about is something like this (depends on whether I understood your problem correctly):
function lookFor(str, digit) {
//validate input...
if (str.length != 8) return false;
if (str[0] != "T" && str[1] != "T") return false;
//start at the end and move to the left as long as there are zeros
//the first non-zero element must be our digit, else return false
for (var i = str.length-1; i>0; --i) {
if (str[i] !== "0") {
return str[i] === digit;
}
}
}
lookFor("TT012000", "2") --> true
lookFor("TT012000", "3") --> false
But I guess the regex solution is probably more compact than this one.
Hi guys i got a problem here, how i can validate a password box that must contain at least one numeric character. i'm not allowed using regular expression / regex. i have tried searching over the web, but the solution is always end with regex.
here's my code that i try
function validateIn()
{
var pass=document.getElementById('password').value;
for(var i=0;i<pass.length;i++)
{
if(isNaN(pass.charAt(i))==false)
{
return true;
break;
}
else
{
return false;
}
}
}
i have tried that way but i fail, can u help me guys? thanks before
One possible approach:
function validateIn() {
var pass = document.getElementById('password').value,
p = pass.length,
ch = '';
while (p--) {
ch = pass.charAt(p);
if (ch >= '0' && ch <= '9') {
return true; // we have found a digit here
}
}
return false; // the loop is done, yet we didn't find any digit
}
The point is, you don't have to return immediately after you have found a normal character (as you're basically looking for a single digit) - you just have to move on with your checking.
Note that I have gone without isNaN, as it's a bit inefficient: the only thing required is a range check.