Question

I've been working on my Safari extension for saving content to Instapaper and have been working on enhancing my title parsing for bookmarks. For example, an article that I recently saved has a tag that looks like this:

Report: Bing Users Disproportionately Affected By Malware Redirects | TechCrunch

I want to use the JavaScript in my Safari extension to remove all of the text after the pipe character so that I can make the final bookmark look neater once it is saved to Instapaper.

I've attempted the title parsing successfully in a couple of similar cases using blocks of code that look like this:

if(safari.application.activeBrowserWindow.activeTab.title.search(' - ') != -1) {
            console.log(safari.application.activeBrowserWindow.activeTab.title);
            console.log(safari.application.activeBrowserWindow.activeTab.title.search(' - '));
            var parsedTitle = safari.application.activeBrowserWindow.activeTab.title.substring(0, safari.application.activeBrowserWindow.activeTab.title.search(' - '));
            console.log(parsedTitle);
};

I started getting thrown for a loop once I tried doing this same thing with the pipe character; however, since JavaScript uses it as a special character. I've tried several bits of code to try and solve this problem. The most recent looks like this (attempting to use regular expressions and escape the pipe character):

if(safari.application.activeBrowserWindow.activeTab.title.search('/\|') != -1) {
            console.log(safari.application.activeBrowserWindow.activeTab.title);
            console.log(safari.application.activeBrowserWindow.activeTab.title.search('/\|'));
            var parsedTitle = safari.application.activeBrowserWindow.activeTab.title.substring(0, safari.application.activeBrowserWindow.activeTab.title.search('/\|'));
            console.log(parsedTitle);
};

If anybody could give me a tip that works for this, your help would be greatly appreciated!

Was it helpful?

Solution

Your regex is malformed. It should be:

safari.application.activeBrowserWindow.activeTab.title.search(/\|/)

Note the lack of quotes; I'm using a regex literal here. Also, regex literals need to be bound by /.

Instead of searching and then replacing, you can simply do a replace with the following regex:

str = str.replace(/\|.*$/, "");

This will remove everything after the | character if it exists.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top