简体   繁体   中英

Javascript - Regex expression to remove special characters from title

I'm attempting to remove special characters from my title and convert it to a url-schema. I'm able to accomplish this by using the .replace method such as: title.replace(/[^A-Za-z0-9\\-/s]/g, " ");

I am running into problems when the title has parentheses in it. I am able to remove the parentheses but it then leaves an empty space at the end which then I am filling empty spaces with a - in order to create a URL schema, this is giving me some issues.

How can I adjust my code below in order to remove the parentheses around (Cat and Dog) in order to not leave a space behind?

This is what's currently happening with my current code: "Pet Supplies Cat and Dog "

 let title = "Pet Supplies (Cat and Dog)" let cleanTitle = "" cleanTitle = title.replace(/[^A-Za-z0-9\\-/s]/g, " "); cleanTitle = cleanTitle.toLowerCase(); cleanTitle = cleanTitle.replace(new RegExp(" ", "g"), "-"); cleanTitle = cleanTitle.replace("-and", ""); cleanTitle = cleanTitle.replace(new RegExp("---", "g"), "--"); cleanTitle = cleanTitle.replace(new RegExp("--", "g"), "-"); console.log(cleanTitle)

My expected outcome is : pet-supplies-cat-dog

You can use

 let title = "Pet Supplies (Cat and Dog)" title = title.toLowerCase() // Turn to lower .match(/[a-z0-9\\s-]+/g) // Extract all alnum + hyphen and whitespace chunks .map(x => x.trim().split(/\\s+/).join("-")) // Trim the items, split with whitespace and join with a hyphen .join("-") // Join the items with a hyphen .replace(/-and\\b/g, ''); // Remove whole word -and console.log(title);

There may be more elegant ways to do it, but you just want to remove special characters at the beginning and the end without adding a space character (or remove it after adding it). That can be done with two additional replacements:

 let title = "Pet Supplies (Cat and Dog)" let cleanTitle = "" cleanTitle = title.replace(/[^A-Za-z0-9\\-/s]/g, " "); cleanTitle = cleanTitle.replace(/^ /g, ""); cleanTitle = cleanTitle.replace(/ $/g, ""); cleanTitle = cleanTitle.toLowerCase(); cleanTitle = cleanTitle.replace(new RegExp(" ", "g"), "-"); cleanTitle = cleanTitle.replace("-and", ""); cleanTitle = cleanTitle.replace(new RegExp("---", "g"), "--"); cleanTitle = cleanTitle.replace(new RegExp("--", "g"), "-"); console.log(cleanTitle)

You can achieve your output in this way:

 let title = "Pet Supplies (Cat and Dog)" let cleanTitle = "" cleanTitle = title.replace(/and/g,''); // removing all "and" cleanTitle = cleanTitle.replace(/\\s+/g, '-'); // replacing all spaces by "-" cleanTitle = cleanTitle.replace(/([()])/g, ''); // removing all "()" cleanTitle = cleanTitle.toLowerCase(); // converting to lowercases console.log(cleanTitle)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM