Difference between * and + in regex javascript [duplicate] - javascript

This question already has answers here:
Regex plus vs star difference? [duplicate]
(9 answers)
Closed 7 years ago.
Both giving the same result so what is the difference between "*" and "+" symbol.
How would I know which one to use.
var str= "oofo fooloo"
var StarSymbol= str.match(/fo*/g);
var PlusSymbol= str.match(/fo+/g)
console.log(StarSymbol) // ["fo", "foo"]
console.log(PlusSymbol) // ["fo", "foo"]
fiddle

You are asking the same question again. So let me explain.
var str= "oofo fooloo"
var StarSymbol= str.match(/fo*/g);
var PlusSymbol= str.match(/fo+/g)
console.log(StarSymbol) // ["fo", "foo"]
console.log(PlusSymbol) // ["fo", "foo"]
Ya, both gives the same result here(for this input) but fo* would match f alone where fo+ would not. * repeats the previous token zero or more times where + repeat the previous token one or more times. So this expects the previous token to be repeated atleast one time.
Example:
> var str= "f"
undefined
> str.match(/fo*/g);
[ 'f' ]
> str.match(/fo+/g);
null
>

o* search's for zero or more o's
o+ search's for one or more o's
go through tutorials

* means between 0 and infinite amount of times, while + means at least one (cannot be zero amount of times)
To be more verbose, * would be like writing {0,}, while + would be like writing {1,}

Related

Replacing charachter by row number in a string [duplicate]

This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed 1 year ago.
So to practice javascript I'm making a little game and I ran into a problem that I have not idea how to solve.
I want to replace the character/letter in the word by a array or index number.
For example "letter"
0: l
1: e
2: t
3: t
4: e
5: r
So in this case I want to change 3th character to character "b" making it to be "letber"
var newStr = myStr.replace(/_/t, "b"); This approach is not optional for me, it would ruin the purpose of my game.
I also took a look into .slice and .replace options but i couldn't figure out how to use it the way I explained.
Substring replace character. substring(start,end) is inclusive on start and exclusive on end. So "hello".substring(1,3) will be 'el'.
var x = "letter"
var index = 3
x = x.substr(0, index) + 'x' + x.substr(index + 1);
console.log(x);
output:
letxer
Actually you are trying to change a character from a string. Which is a primitive type. Since they are immutable values you can't directly change them like array items.
You need to create a new string to get that working.
const word = 'letter';
const changedWord = word.substring(0, 3) + 'b' + word.substring(4);
console.log(changedWord)

Testing if a specific sequence of numbers is somewhere in a integer javascript [duplicate]

This question already has answers here:
How to check whether a string contains a substring in JavaScript?
(3 answers)
What's the best way to convert a number to a string in JavaScript?
(25 answers)
Closed 2 years ago.
I know that this question was asked about in PHP but I could not find anything in javascript.
I have a random number generated between 000(yeah it is just three zero's but it is shown that way from how the number is generated) and 999999999 and I want to test true or false for if whether it includes a specific sequence of numbers like 777, 9000, 28, or the like of any length and from any beginning of numbers...
for example, finding 289 in 678342891 or 728987699 would be true, and finding 289 in 678529187 or 023829564 would be false.
is this possible, and how would I do it?
you can use .includes method in JS after transforming both the number and the other number to strings using .toSting method
let n = 12345589;
let sub = 55;
let sub2 = 25;
function isSeq(number, sub){
number = number.toString(10);
sub = sub.toString(10);
return number.includes(sub);
}
console.log(isSeq(n, sub));
console.log(isSeq(n, sub2));
Check whether your test number is a substring in your long random number. Since you have mentioned that 000 is a value, this tells me that it is a string already(no need to call toString() for it)
var random=678342891;
var search1=289;
var search2=777;
console.log( random.toString().indexOf(search1.toString()) != -1 );//true
console.log( random.toString().indexOf(search2.toString()) != -1 );//false
A function to test it would look like so:
function test(random,search){
return random.toString().indexOf(search.toString()) != -1
}

Why don't my two split statements return the same result? [duplicate]

This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 2 years ago.
I successfully solved the "One Decremented" challenge on Coderbyte, but am wondering why one solution works and the alternative that I tried doesn't. the challenge is to have the function count how many times a digit appears that is exactly one less than the previous digit. (ie: '56' should return 0; '9876541110' should return 6)
This solution works (it logs 6):
var str = '9876541110'
function oneDecremented(str) {
var split = str.split('')
var total = 0
for(let i = 0; i < split.length; i++) {
if(split[i+1] == (split[i] - 1)){
total += 1
} else {}
}
console.log(total)
}
oneDecremented(str)
But if I change the first if statement to the below, the function logs an incorrect 0 for any entry:
if(split[i] == (split[i+1] + 1))
Would anyone be able to help me understand why that is? I'm sure it's a very basic answer that I'm somehow missing...
So your mistake here, and it's a very common mistake, is that you are mixing up addition with string concatenation.
When you do this:
if(split[i] == (split[i+1] + 1))
You are comparing, for example 9 with 8 + 1. But 8 isn't a number, it's a string. And when Javascript sees a string followed by the + operator, it does string concatenation. So instead of comparing 9 with 9, you are comparing 9 with 81
This doesn't happen with the - example because the - operator doesn't work on strings. So Javascript automatically converts both strings to numbers for you and does the subtraction as expected
One kinda goofy way to fix it would be to do this:
if(split[i] == (+split[i+1] + 1))
Putting a + before the string split[i+1] will force javascript to treat split[i+1] as a number because there isn't a unitary string + operator. Do note, however, this adds nothing to the readability of your code and you really might be better served using the - version instead.
The if statement if(split[i] == (split[i+1] + 1)) can also work after some minor changes.
First, as your array split[] is an array of characters, the part where you do split[i+1] + 1 can return an expected result because it will concatenate since, at first, you are trying to increment a character.
To solve this, you could just convert the string elements to integers when making the comparisons, for example:
if(parseInt(split[i]) === parseInt(split[i+1])+1) {...}
I would also avoid using == and use === instead, since === doesn't do type coercion. I hope this answer helps.

JS how to add instead of concatenate numbers [duplicate]

This question already has answers here:
Javascript variables not adding two variables correctly, only concatenating
(3 answers)
Closed 4 years ago.
This question has an answer:
see - Javascript variables not adding two variables correctly, only concatenating
I am trying to add 5 units to a number but the number is being concatenated instead.
this.graphicState[i].shapes[j][k].x += 5
Each time this is run in a loop the outputs are
105.00
105.005
105.0055
105.00555
...
The output I am looking for is,
105.00
110.00
115.00
120.00
...
I tried,
this.graphicState[i].shapes[j][k].x += parseFloat(5)
I also tried this, but get the same results,
this.graphicState[i].shapes[j][k].x = this.graphicState[i].shapes[j][k].x + 5
Thanks,
You need to convert any/all string values to numbers in an expression that has strings as operands with + as the operator. The 5 isn't the issue, this is:
this.graphicState[i].shapes[j][k].x
So, that's what needs to be converted. You can do that easily by prepending a + to it:
+this.graphicState[i].shapes[j][k].x;
Do the conversion on the string first and then use the converted value in your mathematical expression. Here's a simplified example:
var result = "5"
result = +result + 10;
console.log(result);
Try this method
this.graphicState[i].shapes[j][k].x = (parseFloat(this.graphicState[i].shapes[j][k].x) + 5).toFixed(2);

Javascript: Getting last few characters of a string [duplicate]

This question already has answers here:
How can I get last characters of a string
(25 answers)
Closed 5 years ago.
This is a trivial problem if we are storing string in a variable. But out of curiosity, I need to understand how to achieve this without storing string in variable?
// To get first few characters of a string, we can do something like this:
var x = "amangupta".substring(0,7); //amangup
// How to get last 7 characters
var x = "amangupta".substring(this.length - 7, this.length); // does not work, looking for similar approach
var str = "amangupta";
var x = str.substring(str.length - 7, str.length); // will work fine
How to get last 7 characters
Try
"amangupta".slice(-7)
Without an extra variable you need to use the string again
"amangupta".substring("amangupta".length - 7, "amangupta".length);

Categories

Resources