I have simple nextjs app and I am trying to use javascript replace function to replace "-" with empty space " ". But I am getting error as TypeError: Cannot read property 'replace' of undefined. Here is the code
import {useRouter} from 'next/router';
import Layout from '../../components/MyLayout';
const Post = () => {
const router = useRouter();
let resString = router.query.id.replace("-", " ");
return(
<Layout>
<h1>{resString}</h1>
<p>This is the blog post content.</p>
</Layout>
);
}
export default Post;
The problem is that if the query string is empty you does not have the string
property.
First you have to check that the property exists and than use .replace()
like in the following example:
let resString = router.query.id ? router.query.id.replace("-", " ") : "";
Also note that you have to use a regex like in the following example to actually replace all the occurrences:
router.query.id.replace(/-/g, " ");
yes I did that but replacement is not happening . I checked the type of router.query.id its saying its a string but I am not able to call replace function on it . when I try normal string it works.
I have added an image
I tried toString() to convert it to string even this function its showing error
Edited with the solution of the last problem you noticed... use the regex as explained here w3schools.com/jsref/jsref_replace.asp
thanks it worked . But can you explain to me why it didnt work. I am curious