i am trying to do something like this
function findLongestWord(str) {
var wordContainer = str.split(/\b/) || 0;
document.write(wordContainer);
}
findLongestWord("The quick brown fox jumped over the lazy dog");
but this returns
The, ,quick, ,brown, ,fox, ,jumped, ,over, ,the, ,lazy, ,dog
however if i do something like this
function findLongestWord(str) {
var wordContainer = str.split(" ") || 0;
document.write(wordContainer);
}
findLongestWord("The quick brown fox jumped over the lazy dog");
it works as expected and returns
The,quick,brown,fox,jumped,over,the,lazy,dog
so why using /\b/ is different from using " " in split ?
Because " "
is a literal space, and \b
is a word boundary.
Word boundaries occur before the first character in a string, if the first character is a word character, and then again after the last character in the string, if the last character is a word character, and also between two characters in the string, where one is a word character and the other is not a word character, meaning your string looks like this with the boundaries :
"The\b \bquick\b \bbrown\b \bfox\b \bjumped\b \bover\b \bthe\b \blazy\b \bdog"
In other words, you're matching the \b
at the beginning of the word, and at the end of the word, and you're getting the spaces as well, as you're splitting, and end up with
["The"," ","quick"," ","brown"," ","fox"," ","jumped"," ","over"," ","the"," ","lazy"," ","dog"]
If you want to split words on boundaries, you have to add both of them, and anything in the middle, as in /\b.\b/
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments