HTML Encoder in Pasteboard

Before posting more, I needed an html encoder in Pasteboard to change <,>,&,… into <,>&… before pasting into in <pre>code-here</pre>.

I copy text/code into Pasteboard by cmd+c, run the program and cmd+v to paste the encoded string.


- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
    NSPasteboard*  pasteBoard  = [NSPasteboard generalPasteboard];
    // get string from the pasteboard
    NSString* copiedString = [pasteBoard stringForType:NSPasteboardTypeString];
    // html encode
    NSString* encodedString = [NSString HtmlEncode:copiedString];
    // copy it into the pasteboard
    [pasteBoard declareTypes:[NSArray arrayWithObjects:NSStringPboardType, nil] owner:nil];
    [pasteBoard setString:encodedString forType:NSStringPboardType];
    // quit the app
    [[NSApplication sharedApplication] terminate:self];


#import <Foundation/Foundation.h>

@interface NSString (HTML)

+ (NSString*)HtmlEncode:(NSString*)htmlString;


#import "NSString+HTML.h"

@implementation NSString (HTML)

+ (NSString*)HtmlEncode:(NSString*)htmlString {
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"&"  withString:@"&amp;"];
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"<"  withString:@"&lt;"];
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@">"  withString:@"&gt;"];
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"""" withString:@"&quot;"];    
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"'"  withString:@"&#039;"];
    return htmlString;


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.