0

I want to separate some words with JSON and print underlined words with JSON

JSfiddle without JSON

Example JSON Data: {'term':'word1','term':'word2','term':'word3',..}

What have I done?

function wrapSentence(sentence) {

    $.getJSON( "ajax/test.json", function( data ) {
      var items = [];
      $.each( data, function( key, terms ) {

      // Get element contents and split by whitespace git
                var words = $sentence.text().split(/\s+/);
                // Create an empty array for storing wrapped elements
                var wrapped = [];
                // Loop through each word and wrap
                for (var i = 0; i < words.length; i++) {
                    if(words[i] != terms) {
                        wrapped.push('<span>' + words[i] + '</span>');
                    } else {
                        wrapped.push('<span style="text-decoration: underline;text-decoration-style:dashed;">' + words[i] + '</span>');
                    }
                }
                // Combine words into a string
                return wrapped.join(' ');

      });

    });


}

I can get data with getJSON, but I can't print. What could be the reason for this?

Editor
  • 622
  • 1
  • 11
  • 24
  • There doesn't seems to be any `$sentence` variable, you've probably meant to use `sentence`. – Titus May 12 '19 at 09:31
  • Please check again the question or refresh page @Titus - Also dont down vote :) – Editor May 12 '19 at 09:33
  • I see, then the problem is probably the `return wrapped.join(' ');` statement inside the `forEach` callback. You should check out how you can return a value from an async function. – Titus May 12 '19 at 09:37
  • I'm trying to understand, but I don't understand. I should be move `return wrapped.join(' ');` inside `for (var i = 0; i < words.length; i++) {` ? @Titus – Editor May 12 '19 at 09:46
  • No, the problem is that the `wrapSentence` will return before the async call is settled, take a look at https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call to see how you can fix that. – Titus May 12 '19 at 09:54
  • Unfortunately, I was not successful. Now I'm going to try to create a second `function wrapSentence(sentence)` @Titus - Thank you for your time – Editor May 12 '19 at 10:28

0 Answers0