Automator services replace selected text's spaces with underscore
Here is one example of how it can be achieved using an Automator Service and a Run AppleScript action:

on run {input}
    set input to replaceText(" ", "_", input as string)
end run

on replaceText(find, replace, textString)
    set prevTIDs to AppleScript's text item delimiters
    set AppleScript's text item delimiters to find
    set textString to text items of textString
    set AppleScript's text item delimiters to replace
    set textString to "" &amp; textString
    set AppleScript's text item delimiters to prevTIDs
    return textString
end replaceText



Set the service to the settings shown in the image below:


Note that in macOS Mojave a service is now called a Quick Action.






Note that the replaceText(find, replace, textString) handler was something I found on the Internet too many years ago to remember where and give credit to its source.