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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With