Position of the first word of a string in Javascript

I originally used indexOf to find a space, but I want to find any word boundary.

Something like this, but what is the regular expression?

var str = "This is a sentence",
firstword = str.search("");
return word;

I want to return "This". Even in the case of a tab, period, comma, etc.

+3
source share
2 answers

Something like that:

var str = "This is a sentence"; 
return str.split(/\b/)[0];

Although you probably want to check that there was such a match:

var str = "This is a sentence"; 
var matches = str.split(/\b/);
return matches.length > 0 ? matches[0] : "";
+11
source

This divides the line at each word boundary and returns the first:

var str = "This is a sentence";
firstword = str.split(/\b/)[0];
+3
source

Source: https://habr.com/ru/post/1752562/


All Articles