skip to Main Content

I have to get keywords from the client and need to remove all spaces next to commas.

I have the following keywords list style

  ,air duster, apple,       samsung , power bank station,sony

I need like this

air duster,apple,samsung,power bank station,sony

my code

 $("#my-input").on("focusout", function() {  
    console.log("FOCUS OUT")

    $(this).attr("value",$(this).val().split(/[ ,]+/).join(',').trim());
  })

print

,air,duster,apple,samsung,power,bank,station,sony

2

Answers


  1. ',air duster, apple,       samsung , '.replace(/, +/g, ',')
    
    Login or Signup to reply.
  2. You can use

    console.log(
        "  ,air duster, apple,       samsung , power bank station,sony".split(",").map(x => x.trim()).filter(Boolean).join(",")
    )
    // => air duster,apple,samsung,power bank station,sony

    Here,

    • .split(",") – splits with a comma
    • .map(x => x.trim()) – removes leading/trailing whitespaces
    • .filter(Boolean) – removes empty items
    • .join(",") – join the items with a single comma.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search