I have a database of book titles where string values are stored. A php script reads the data and displays them. The problem is happening when a Book title contains the ' character - as apostrophy let's say. One example is the title "The Devil's Alternative".

So when I write
var Title = <?php echo($Title) ?>;
it's becoming
var Title = 'The Devil's Alternative' ;

and giving an error as the quotes do not match.

How do I avoid this problem ? Also how to avoid some other character combinations (for example // or /* -- javascript will turn them into comments and generate errors)

It works if I replace the single quote with a "\'" (backslash before the single quote. So
$Title = str_replace("'", "\'", $Title);

var Title = <?php echo($Title) ?>;
works fine

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.