Skip to content Skip to sidebar Skip to footer

How To Split Words Using Javascript

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,

Solution 1:

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.


Solution 2:

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>

Solution 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


Solution 4:

Just use this code:

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

Solution 5:

a.split(',')

or

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

Post a Comment for "How To Split Words Using Javascript"