简体   繁体   English

带有特殊字符'/'的字符串中的Javascript子字符串字符

[英]Javascript substring character from string with special character '/'

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. 我的日期格式为yyyy/mm/dd ,我想提取月份。 However, with the code above, when I tried substr(5,6) , it returns me '01/23' rather than '01 ' itself. 但是,使用上面的代码,当我尝试使用substr(5,6) ,它返回的是“ '01/23'而不是“ '01 ”本身。

The second parameter of substr is length , so you need 2 instead of 6 here: substr的第二个参数是length ,所以这里需要2而不是6:

 var str = "2017/01/23"; console.log( str.substr(5, 2) ) 

我想你想要str.substring(5,7)!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM