1

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 ?

2
  • 1
    \b is a word boundary, and a space matches the space. So, there is nothing strange in the results you get. Commented May 1, 2016 at 21:50
  • Also your defaulting case is useless as split will always return an array Commented May 1, 2016 at 21:51

2 Answers 2

2

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/

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

1 Comment

Perfect answer , now i got where i was wrong .thanks mate
2

\b a Matches a zero-width word boundary, such as between a letter and a space.

while using split(' ') only matches spaces:

Docs on Regex from MDN

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.