Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
83
rated 0 times [  85] [ 2]  / answers: 1 / hits: 19394  / 8 Years ago, wed, august 17, 2016, 12:00:00

Im very new to javascript Im working through the w3school tutorial, trying to replace all occurrences within a certain string.



I have the following string 08/18/16 I would like to replace all occurences of / to ,



As per W3schools example I try to achieve the above as follow:



date1 = str.replace(/,,);



However the above results in an error




ReferenceError: str is not defined date1 = str.replace(/,,)




I would really appreciate it if someone could give the following code a scan.



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(/,,);

More From » jquery

 Answers
53

ReferenceError: str is not defined




The issue tells you that the str variable should be defined first to be able to perform a replace on it.



To replace all / with , you need a ///g (where /.../ are the regex delimiters, / matches a literal / and g enables global, multiple replacements) regex as a replace with a string as the first argument will only replace once:





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




[#61013] Sunday, August 14, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
everardo

Total Points: 406
Total Questions: 104
Total Answers: 92

Location: Albania
Member since Sun, Nov 22, 2020
4 Years ago
;