Reputation: 13
What is javascript function that opposite of indexof() ?
In this my code when you press button. It's will show 3
[from indexof(".")
].
But I want function that opposite of indexof()
, That show me 2
[decimal]
<!DOCTYPE html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "150.20";
var n = str.indexOf(".");
document.getElementById("demo").innerHTML = n;
}
</script>
</body>
</html>
Upvotes: 1
Views: 2614
Reputation: 74738
Try with this:
str.split(".")[1].length;
You can split the string at the "."
with .split()
method and get the second index with [1]
and calculate the length of it.
As Der Vampyr commented so i think there should be so you can update it with this:
function myFunction() {
var str = "150.22";
var dot = str.indexOf(".");
var n = (dot != -1) ? str.split(".")[1].length : "This value does not have decimals.";
document.getElementById("demo").innerHTML = n;
}
Upvotes: 2
Reputation: 338
This specific problem can be better resolved by using split('.')[1]
like Jai's answer, but I think most of the people who fall here through Google actually want a reversed version of indexOf()
. lastIndexOf()
doesn't help in this case, because it returns the actual index counting from the beginning and not from the end. It searches from the end, but returns the actual index.
One easy way to achieve this is by reversing the string
before using indexOf()
:
const str = "150.20";
const n = str.split('').reverse().join('').indexOf('.');
Explanation:
const n = str
.split('') // this will return an array with each character as an item
.reverse() // this will reverse the array
.join('') // this will join the reversed array back into a string (which is optional at this point, because you don't really need the reversed string. Only the index)
.indexOf('.') // this will return the index in which the . appears in the reversed order
Upvotes: 0
Reputation: 324790
Somewhat unsurprisingly, lastIndexOf
will help here.
The only catch is that it still numbers from the end of the string, so you would have to do something like str.length - str.lastIndexOf(".") - 1
to get the 2
you are looking for. There is no built-in function for this.
Upvotes: 3