You will need to create a custom processor inside renderField
pipeline to replace space with dashes in external urls inside RTE.
- Firstly you will need to create a custom processor as below, that converts the
Html
inside RTE to HtmlDocument
that can be used for searching href attributes in the HTML
dom and replacing their values as desired.
using HtmlAgilityPack;
using Sitecore;
using Sitecore.Diagnostics;
using Sitecore.Pipelines.RenderField;
using System;
using System.Linq;
public class EncodeExternalLinks
{
public virtual void Process(RenderFieldArgs args)
{
Assert.ArgumentNotNull((object)args, nameof(args));
if (Context.PageMode.IsExperienceEditorEditing)
return;
if (args.FieldTypeKey == "rich text")
{
var richTextHtml = args.Result.FirstPart;
var doc = new HtmlDocument();
doc.LoadHtml(richTextHtml);
var anchorNodes = doc.DocumentNode.SelectNodes("//a[@href]");
if (anchorNodes != null && anchorNodes.Any())
{
foreach (var anchorNode in anchorNodes)
{
Uri originalUrl;
var hrefAttribute = anchorNode.Attributes.Where(x => x.Name.Equals("href"))?.FirstOrDefault();
if (hrefAttribute != null && Uri.TryCreate(hrefAttribute.Value, UriKind.Absolute, out originalUrl))
{
hrefAttribute.Value = hrefAttribute.Value.Replace(" ", "-");
}
}
args.Result.FirstPart = doc.DocumentNode.InnerHtml;
}
}
}
}
- Thereafter you need to patch the custom processor created above as below after the
ExpandLinks
processor under the renderField
pipeline.
<?xml version="1.0"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/">
<sitecore>
<pipelines>
<renderField>
<processor patch:after="*[@type='Sitecore.Pipelines.RenderField.ExpandLinks, Sitecore.Kernel']" type="SitecoreCustomExtensions.Pipelines.EncodeExternalLinks,SitecoreCustomExtensions" resolve="true" />
</renderField>
</pipelines>
</sitecore>
</configuration>
Once the above changes are done, external link inside RTE will have spaces in the url replaced with dash(-). Let me know in case you have any doubts.
Hope this helps!!!