Create new field from existing using regex

Hi everyone!
I’ve been pretty successful using Client Scripts to manage passing and populating data between DocTypes but am a bit stuck on this one -

I am extending the functionality of the Items DocType to contain a little more data for an e-commerce platform. I need to create a “permalink” field from the Item Name field. Currently, item names might look like this: Some Artist / Some Title (Limited Edition)

I need to spit that name back into a field on the same DocType but removing the non-alphanumeric characters, making it all lowercase, and replacing all the spaces with hyphens to get this result: some-artist-some-title-limited-edition

How could I achieve this in a client script? Any and all help is appreciated!

Thanks!
Dan

Hi,

Here’s a simple JavaScript function to convert a given text string into permalink URL format

function permalink(text) {       
    var characters = [' ', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '+', '=', '_', '{', '}', '[', ']', '|', '/', '<', '>', ',', '.', '?', '--']; 

    for (var i = 0; i < characters.length; i++) {
         var char = String(characters[i]);
         text = text.replace(new RegExp("\\" + char, "g"), '-');
    }
    text = text.toLowerCase();
    return text;
}

alert(permalink("your text here"));

You can incorporate the same in your DocType client script and pass data to the new field using the main input text field.

Here’s the live version of the code to test it out: https://jsfiddle.net/1vb9rj60/