0

I have this text in my mysql-database:

Hi
how are you?

Working (php):

echo $row['text'];

Now working:

<script>
test = "<?php echo $comment; ?>";
document.writeln(test.parseURL().parseUsername().parseHashtag());
</script>

The error is nothing printed.

The javascript function:

 <script>
String.prototype.parseURL = function() {
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.=]+/g, function(url) {
return url.link(url);
});
};

String.prototype.parseUsername = function() {
return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
    var username = u.replace("@","")
    return u.link("http://url.com/"+username);
});
};

String.prototype.parseHashtag = function() {
return this.replace(/[#]+[A-Ö–a-ö0-9-_]+/g, function(t) {
    var tag = t.replace("#","")
    return t.link("/?p=tagga&q="+tag);
});
};
</script>

But if I have it without the line break so it works Hi! How are you?

Anyone know how I can solve this?

2 Answers 2

2

Always look at the rendered output. In this case:

test = "Hi
how are you?";

This is clearly invalid (unterminated string constant).

When dumping PHP variables into JS, ALWAYS use json_encode.

test = <?=json_encode($row['text'])?>;

Output:

test = "Hi\nhow are you?";
Sign up to request clarification or add additional context in comments.

Comments

0

Javascript literal multiline strings are nothing like multiline line strings in PHP. Either escape the newline e.g.

var text = 'Hi \
how are you?'

Or make it one single line e.g.

var text = 'Hi\nHow are you?';

2 Comments

To save in database: $ text = mysql_real_escape_string ($ _POST ['tag']); What code should I use instead?
Saving is not the problem. It's the ouput. You will need to make sure it's proper javascript.

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.