var data = null var number = data.replace(/[^0-9]/g,''); -> Uncaught TypeError: Cannot read property 'replace' of null var data = 1 var number = data.replace(/[^0-9]/g,''); Uncaught TypeError: data.replace is not a function if (data) {var value = ('' + data).replace(/[^0-9]/g,'');} or if (data) {var value = new String(data).replace(/[^0-9]/g,'');}