0

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

2
  • Well the query string is undefined. const resString = router.query.string ? router.query.string.replace("-", " "): ''; Commented Jan 31, 2020 at 11:17
  • sorry its router.query.id not string but still I am getting same error when I changed it to id Commented Jan 31, 2020 at 11:20

1 Answer 1

3

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, " ");
Sign up to request clarification or add additional context in comments.

6 Comments

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
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.