Reputation: 2471
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;
Upvotes: 0
Views: 3012
Reputation: 4489
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, " ");
Upvotes: 3