Search code examples
jqueryvarencodeuricomponent

why cant i put a var in a encodeURI?


why is this working?

var movieName = encodeURI("deadpool");
var url = "https://api.themoviedb.org/3/search/movie?api_key=" + apiKey + "&query=" + movieName;

and this not?; iven put a console log to check and that works

var movieName = $(".shown .title").html();
console.log(movieName);

var url = "https://api.themoviedb.org/3/search/movie?api_key=" + apiKey + "&query=" + encodeURI(movieName);

Solution

  • The HTML may have whitespace around the title, which you need to remove.

    var movieName = $(".shown .title").html().trim();
    

    Also, you should probably use .text() rather than .html(), in case there are embedded HTML tags.

    var apiKey = "key";
    
    var movieName = encodeURIComponent("deadpool");
    var url = "https://api.themoviedb.org/3/search/movie?api_key=" + apiKey + "&query=" + movieName;
    console.log(url);
    
    var movieName = $(".shown .title").html().trim();
    console.log(movieName);
    
    var url = "https://api.themoviedb.org/3/search/movie?api_key=" + apiKey + "&query=" + encodeURIComponent(movieName);
    console.log(url);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="shown">
    <div class="title">
    deadpool
    </div>
    </div>