Ad

Javascript Substring Character From String With Special Character '/'

- 1 answer

I am trying extract some characters from string. I tried the example at here by using these code:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to extract parts of the string.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var str = "2017/01/23";
    var res = str.substr(5, 6);
    document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>

My date format as yyyy/mm/dd and I wanted to extract the month out. However, with the code above, when I tried substr(5,6), it returns me '01/23' rather than '01' itself.

Ad

Answer

The second parameter of substr is length, so you need 2 instead of 6 here:

var str = "2017/01/23";

console.log(
  str.substr(5, 2)
)

Ad
source: stackoverflow.com
Ad