13

This might be a simple question but, how do i split words... for example

a = "even, test"

I have used .split to seperate the text with space.

so the result came is like

a = "even,"
b = "test"

But, how do I remove the 'comma' here?

But in some conditions it might get "even test" and in some conditions i might get "even, test". All are dynamic, so how do i check it for both?

Thanks

4
  • 3
    a.split(/\W+/).filter(x => x); Commented Apr 5, 2018 at 7:50
  • Does this answer your question? How do I split a string, breaking at a particular character? Commented Dec 11, 2019 at 16:10
  • @ChoerunAsnawi Why do you need the filter there? Is it filtering anything at all if it's just x => x? Commented Apr 3, 2021 at 7:48
  • @AndrewBrown map(x => x) would be a NO-OP. filter(x => x) is not a NO-OP; it treats x like a boolean to filter on. An empty string, when treated like a boolean, is like false. This means that "foo " will be correctly split as ["foo"] instead of incorrectly split as ["foo", ""]. Commented Jun 12 at 11:42

7 Answers 7

15

Firstly, the split() function is not jQuery - it is pure Javascript.

Did you try doing split with a comma and a space? That would have worked just fine in your case:

var result = input.split(', ');

For more complex splits, you can use regular expression pattern matching to allow multiple commas or spaces between the two fields:

var result = input.split(/[, ]+/);

but you probably don't need to go that far in your case.

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

Comments

4

I think is better to use something like this:

text.match(/[a-z'\-]+/gi);

Example:

var e=function()
 {
  var r=document.getElementById('r');
  var x=document.getElementById('t').value.match(/[a-z'\-]+/gi);
  for(var i=0;i<x.length;i++)
   {
    var li=document.createElement('li');
    li.innerText=x[i];
    r.appendChild(li);  
   }
 }
<div style="float:right;width:18%">
 <ol id="r" style="display:block;width:auto;border:1px inner;overflow:scroll;height:8em;max-height:10em;"></ol>
 <button onclick="e()">Extract words!</button>
</div>
<textarea id="t" style="width:70%;height:12em">even, test; spider-man

But saying o'er what I have said before:
My child is yet a stranger in the world;
She hath not seen the change of fourteen years,
Let two more summers wither in their pride,
Ere we may think her ripe to be a bride.

—Shakespeare, William. The Tragedy of Romeo and Juliet</textarea>

Comments

3

I found a list of word separators in Sublime Text default settings. Here's how to split with it, with some Unicode support (the defined separators are not Unicode though):

{ // word_separators: ./\()"'-,;<>~!@#$%^&*|+=[]{}`~?: (32)
    function splitByWords(str = '', limit = undefined) {
        return str.split(/[-./\\()"',;<>~!@#$%^&*|+=[\]{}`~?:]/u, limit)
    }

    function reverseString(str) {
        let newString = ''
        for (let i = str.length - 1; i >= 0; i--)
            newString += str[i]
        return newString
    }

    const str = '123.x/x\\x(x)x"x\'x-x:x,789;x<x>x~x!x@x#x$x%x^x&x*x|x+x=x[x]x{x}x`x~x?456'
    console.log(splitByWords(str)) // (33) ["123", "x", "x", "x", "x", "x", "x", "x", "x", "x", "789", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "456"]
    console.log(splitByWords(str, 1)) // ["123"]
    console.log(splitByWords(reverseString(str), 1)) // ["654"]
}

For some reason the - has to be at the beginning, and the : at the end. Edit: you might want to add \s (after the -) to count whitespace as separator

Comments

1

Just use this code:

var a = "even, test";
var words = a.split(", ");

3 Comments

Thanks, but in some conditions i might get "even test" and in some conditions i might get "even, test". so how do i check it for both?
The answer has been given to you by @Spudley. Use regular expression: a.split(/[, ]+/);
@Harry: Also, with mine it use any non-word text as a separator (only extracts words).
1
a.split(',')

or

var re = /\s*,\s*/
var newA = a.split(re);

Comments

1

I think you could do it like this:

var a= 'even,'
var newA = a.slice(0, -1)

This will remove the last char from a given string.

And to check if the string contains a comma, I would do the following:

if (a.indexOf(",") >= 0){
    //contains a comma
} else {
    //no comma
}

I am a javascript beginner, so this probably is not the best way to do it, but nevertheless it works.

Comments

0

Hej Harry

if the comma is the separator you can call split with the comma

Ex:

var newColls = myString.split(",");

and not split with space.

GL

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.