Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,"
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

like image 386
Harry Avatar asked Oct 05 '11 11:10

Harry


People also ask

How do you split text in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

Can we split object in JavaScript?

JavaScript split() Method: String ObjectThe split() method is used to split a string object into an array of strings by breaking the string into substrings. separator: The character to separate the string. The separator itself is a string.

How do I split a string in TypeScript?

The split() is an inbuilt function in TypeScript which is used to splits a String object into an array of strings by separating the string into sub-strings. Parameter: This method accepts two parameter as mentioned above and described below: separator – This parameter is the character to use for separating the string.


1 Answers

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

like image 130
Rivenfall Avatar answered Oct 24 '22 02:10

Rivenfall