0

I am working with an API that accepts an array of strings from an input field called #tags. What is the best way to do that? It should also remove any commas between the "tags" and be [] if no tags.

input: tag1, tag2, tag3 becomes: ["tag1", "tag2", "tag3"]

HTML

<input id="tags" type="text" placeholder="tags" name="" value="">

how im currently getting the tag value:

createPost('canvasID',{tags:$('#tags').val()});
1
  • myString.split(',') will become ["tag1", "tag2", "tag3"] Commented Jul 3, 2013 at 14:50

4 Answers 4

7

Use split function:

var valueInserted = $("#tags").val(); // "tag1,tag2,tag3, "two words""
var tags = valueInserted.split(",");  // ["tag1", "tag2", "tag3", "two words"]

Also, trim() your strings from tags array:

for (var i in tags) {
    tags[i] = tags[i].trim();
}

JSFIDDLE

Or inline, using regex:

 var tags = $('#tags').val().split( /,\s*/ );

JSFIDDLE

Documentation can be found here.

Sign up to request clarification or add additional context in comments.

3 Comments

$.trim() if you wish to support older IE version, anyway +1
@Karl-AndréGagnon Thanks. I prefer to split and then to trim.
@roasted I don't care about IE while I am a Linux fan, but thanks for vote! :-)
1

You can split the string by using a regex that looks for a comma followed by possible whitespace:

var yourArray = $('#tags').val().split( /,\s*/ );

and then

createPost('canvasID',{tags: tagsArray});

Comments

0

Use the split function.

createPost('canvasID',{tags:$('#tags').val().split(',')});

Comments

0

   var res = name.replace(/["]+/g, ""); // remove """"               

 

   global with /g
   var resa = res.replace(/[[]+/g, ""); // remove [
   var reso = resa.replace(/[,]+/g, "");// chop            //,,,,,
   str = reso.substring(0, reso.length - 1);//         finally   chop off last ]
// you can chop off all double quotes after 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.