Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
20
rated 0 times [  23] [ 3]  / answers: 1 / hits: 5295  / 3 Years ago, sun, august 1, 2021, 12:00:00

Total noob here, I'm currently studying regex in javascript. I have a function that is supposed to pick numbers between 0 and 9 from a string. The function works fine as long as the variable it searches has letters or numbers, however when a null value is entered it gives out the following error:


Uncaught: TypeError: Cannot read property 'toString' of null


How can I fix this? Thank you in advance.


Here is the code:


var lause  = "s0m3 p30pl3";
function tulostanumerot();
var numerot = /[0-9]/g;
var testi = numerot.test(0-9);

var setti = lause.match(numerot);
if (testi === true) {
console.log(setti.toString());
}
else {
console.log("Ei numeroita!");
};

More From » regex

 Answers
8

A few notes about your code:



  • The method test() takes a string argument, which makes this not correct var testi = numerot.test(0-9);



  • The code is not inside the function function tulostanumerot();



  • You can omit testi at all, and only use setti



  • Note that match() returns either an array or null, so you can use if (setti) { instead of checking for true




The code might look like


function tulostanumerot() {
var numerot = /[0-9]/g;
var setti = lause.match(numerot);

if (setti) {
console.log(setti.toString());
} else {
console.log("Ei numeroita!");
}
}
tulostanumerot();



function tulostanumerot(lause) {
var numerot = /[0-9]/g;
var setti = lause.match(numerot);

if (setti) {
console.log(setti.toString());
} else {
console.log(Ei numeroita!);
}
}

[
s0m3 p30pl3,
,
test
].forEach(v => tulostanumerot(v));




[#1033] Sunday, July 25, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tierra

Total Points: 705
Total Questions: 85
Total Answers: 96

Location: Maldives
Member since Sat, Jan 29, 2022
2 Years ago
tierra questions
;