Forum Moderators: open

Message Too Old, No Replies

Getting rid of certain characters

Need to strip out punctuation, etc.

         

MatthewHSE

8:03 pm on Oct 22, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm trying to create a little script that will write a textarea with ready-made HTML markup to link to the page being viewed. I've got it all figured out to get the document title, the URL, and all the other necessary stuff. What I don't know is how to deal with potential puctunation in the page title. Here's what I have so far, and it works great:

var url = window.location;
var title = document.title;
document.write ('<textarea cols=20 rows=3><a href="'+url+'" title="'+title+'">'+title+'</a></textarea>');

The problem is that the page titles are generated dynamically. They may occasionally have single or double quotes, or possibly other characters that would mess things up. Javascript seems to print them all inside the textarea okay, but obviously extra quotes would make the link fail when the text has been copied onto a webpage.

Is there a way around this, like some way to strip out specified characters from the page title?

Alternatively, and entirely unrelated to javascript, is it necessary for SE purposes to include the title attribute in the <a> tag, when it would be identical to the anchor text?

dmorison

8:15 pm on Oct 22, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Looks like you need JavaScript's escape() function, which will make any string URL safe, converting spaces to "+" and single / double quotes (along with any other non alpha-numeric characters) into their %xx equivalents.

[edited by: dmorison at 8:24 pm (utc) on Oct. 22, 2004]

dmorison

8:21 pm on Oct 22, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



How about this - using .replace to make the title safe aswell:

var url = escape(window.location);
var title = document.title.replace("'","&quot;");
document.write ('<textarea cols=20 rows=3><a href="'+url+'" title="'+title+'">'+title+'</a></textarea>');