1

I have a problem with a variable string but return [Object object]

$(document).ready(function () {
    $(".story-area > h1").text(function () {
        return $(this).text(convertString($(this).text()));
    });

    $(".story-area > p").text(function () {
        return $(this).text(convertString($(this).text()));
    });

    $(".story-area > div > p").text(function () {
        return $(this).text(convertString($(this).text()));
    });
});


function convertString(current_text) {
    var arr_text = current_text.split(' ');
    var new_text = '';
    for (i = 0; i < arr_text.length; i++) {
        if (arr_text[i].length > 4) {
            new_text += arr_text[i].replace(/[Hh][Ii]/g, 'HIV') + ' ';
        } else {
            new_text += arr_text[i] + ' ';
        }
    }
    return new_text;
}

The new_text value returns [Object object] instead of the string value. Any errors on my code?

enter image description here

6
  • 1
    Uggh, what do you mean? It is replacing the texts for the specified jquery object Commented Sep 30, 2015 at 16:07
  • I did a jsfiddle and your function seems works : jsfiddle.net/alex3165/Lqsdb0nz Commented Sep 30, 2015 at 16:12
  • 1
    how did you conclude that new_text is [Object object]? $(this).text(convertString($(this).text())) is an object. Commented Sep 30, 2015 at 16:12
  • Just edited my question with the screenshot of my output. @kalyptusprod Commented Sep 30, 2015 at 16:15
  • 2
    FIWIW, the whole code can be simplified to $(".story-area > h1, .story-area > p, .story-area > div > p").text(convertString). Also why don't you link to the fiddle, or better create a runnable demo here? Commented Sep 30, 2015 at 16:18

1 Answer 1

3

AH, you are setting the text inside of setting the text! You are treating text() as an each.

$(".story-area > h1").text(function () {
    return convertString($(this).text());
});
Sign up to request clarification or add additional context in comments.

1 Comment

This worked! But someone already mentioned this earlier but thank you!!

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.