Find & replace text in a URL

I have a script that reads a URL in txt files and opens them in Safari (that’s run automatically by Hazel).

What I’d like it to do if possible is if the link contains https://mobile.twitter.com/username. then I’d like to replace it with https://twitter.com/username. so that it opens the normal desktop version rather than the mobile version on my Mac. Each txt file contains 1 URL, nothing else.

The script I use the get the URLs and open them is:

set theURL to read theFile

tell application “Safari”
activate
open location theURL
end tell

Any help would be appreciated.

Hello.

It makes it a bit easier to read if you use the applescript tags you see at the top of the edit box, anyways, the snippet below works for me. I don’t know how you run this thing, so I have commented out some error handling code, which you may want to use, or not, depending on your workflow.

set theFile to POSIX path of ((path to desktop as text) & "mytweet.txt")
# try
set theURL to read theFile
# on error 
# display dialog "Problem finding the file"
# error number -128
# end try

set {tids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "mobile."}
# (hopefully you haven't any friends with the name mobile.)
set desktopURL to text items of theURL
set AppleScript's text item delimiters to tids
set theURL to desktopURL as text
tell application "Safari"	
	activate
	open location theURL
end tell

That works great. Thanks a lot for the help! :slight_smile:

.One more question.

If I wanted to add another instance to this script how would I do that? For example with this Amazon link http://www.amazon.co.uk/gp/aw/s/ref=is_box_?k=usb+flash+drive+64gb+3.0 I’d like to strip out “gp/” to open as the desktop version instead of the mobile version.

Hi,

this is a different solution to handle multiple URL’s


property URLList : {{|URL|:"https://mobile.twitter.com", cut:"mobile."}, {|URL|:"http://www.amazon.co.uk/gp", cut:"/gp"}}

set theURL to "http://www.amazon.co.uk/gp/aw/s/ref=is_box_?k=usb+flash+drive+64gb+3.0"

repeat with anURL in URLList
	if theURL begins with anURL's |URL| then
		set cutOffset to offset of anURL's cut in theURL
		tell theURL to set newURL to text 1 thru (cutOffset - 1) & text (cutOffset + (length of anURL's cut)) thru -1
		tell application "Safari"
			activate
			open location newURL
		end tell
		exit repeat
	end if
end repeat


Thanks.

Strangely it compiles fine in AppleScript Editor, but when I add it to Hazel (changing set theURL to “http://www.amazon.co.uk/gp/aw/s/ref=is_box_?k=usb+flash+drive+64gb+3.0” to set theURL to read theFile) it says:

Expected “end” but found “property”.

Not sure if that’s a problem with Hazel or the script.