Warm tip: This article is reproduced from stackoverflow.com, please click
javascript reactjs next.js

javascripts default replace function not working in nextjs

发布于 2020-03-31 22:55:37

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;

enter image description here

Questioner
sriram hegde
Viewed
28
Emanuele Scarabattoli 2020-01-31 19:29

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, " ");