PROWAREtech
ASP.NET Core: How to Create WordPress Slugs
Use C# regular expressions (Regex) to create slugs with only standard characters for use in a URL or other purpose.
Use the regular expression \W+
to replace unwanted URL characters with a dash (-) and prevent multiple dashes running together. In other words, sanitize names and titles.
See also: do this in a console application and use JavaScript regular expressions to create WordPress slugs.
This is a Controller in an MVC web application.
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
private IWebHostEnvironment env { get; }
public HomeController(IWebHostEnvironment env)
{
this.env = env;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(IFormCollection form)
{
string input = form["input-field"];
string slug = System.Text.RegularExpressions.Regex.Replace(input, @"\W+", "-"); // NOTE: turn the input text into a slug
return View(model: slug);
}
}
}
And now the View code.
@{
ViewData["Title"] = "/Home/Index";
}
<div class="text-center">
<h1 class="display-4">Get Slug</h1>
<form method="post">
<div>
<input type="text" name="input-field" placeholder="input..." />
</div>
<div>
<button type="submit" class="btn btn-primary">SUBMIT</button>
</div>
</form>
@if(Model is string)
{
<p>@Model</p>
}
</div>
Comment