ReferenceError:未定义str

时间:2016-08-17 06:53:27

标签: javascript jquery string

我是javascript的新手我正在使用w3school tutorial,尝试替换某个字符串中的所有匹配项。

我有以下字符串08/18/16我想将/的所有出现替换为,

根据W3schools的例子,我尝试按照以下方式实现上述目标:

date1 = str.replace("/",",");

但是上述情况会导致错误

  

ReferenceError:str未定义date1 = str.replace(" /",",")

如果有人可以提供以下代码进行扫描,我将非常感激。

var firstDate = document.getElementById("firstDate").value;
var secondDate = document.getElementById("secondDate").value;
var date1 = firstDate.substring(0,11);
var date2 = secondDate.substring(0,11);
date1 = str.replace("/",",");
date2 = str.replace("/",",");

5 个答案:

答案 0 :(得分:2)

  

ReferenceError:str未定义

问题告诉您应首先定义str变量,以便能够对其执行replace

要将{em>所有 /替换为,,您需要/\//g(其中/.../是正则表达式分隔符,\/匹配文字/g启用全局,多个替换)正则表达式为replace,字符串作为第一个参数只会替换一次:



var str = "08/18/16";
var res = str.replace(/\//g, ",");
console.log(res);




答案 1 :(得分:0)

您没有任何名为str的变量,因此无效。 试试这段代码:

  var firstDate = document.getElementById("firstDate").value;
    var secondDate = document.getElementById("secondDate").value;
    var date1 = firstDate.substring(0,11);
    var date2 = secondDate.substring(0,11);
    date1 = date1 .replace("/",",");
    date2 = date2 .replace("/",",");

答案 2 :(得分:0)

您无法声明str变量,因此请声明为var str

var firstDate = document.getElementById("firstDate").value;
var secondDate = document.getElementById("secondDate").value;
var str;
var date1 = firstDate.substring(0,11);
str = date1;
date1 = str.replace("/",",");
var date2 = secondDate.substring(0,11);
str = date2;    
date2 = str.replace("/",",");

答案 3 :(得分:0)

var dateStr = "08/18/16";
var individualStr = dateStr.split('/');
var newStr = individualStr[0]+','+individualStr[1]+','+individualStr[2]

答案 4 :(得分:0)

var firstDate = document.getElementById("firstDate").value;
var secondDate = document.getElementById("secondDate").value;
var date1 = firstDate.substring(0,11);
var date2 = secondDate.substring(0,11);
date1 = str.replace("/",",");
date2 = str.replace("/",",");

此代码在这里不起作用,因为java脚本中的replace可以用于字符串,但是你从id获取的值作为日期格式,这就是为什么它不起作用。

replace只会替换第一次发生的事件。使用正则表达式在控制台中尝试此代码,它将替换所有。

var firstDate = "31/11/2016";
var secondDate = "31/11/2016";
var date1 = firstDate.substring(0,11);
var date2 = secondDate.substring(0,11);
date1 = date1 .replace(/\//g,",");
date2 = date2 .replace(/\//g,","); 
alert(date1);
alert(date2);