简体   繁体   English

Javascript中字符串的第一个单词的位置

[英]Position of first word of string in Javascript

I originally used indexOf to find a space but I want to find any word boundary. 我最初使用indexOf来查找空格,但我想找到任何单词边界。

Something like this, but what regex? 像这样的东西,但是什么正则表达式?

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. 即使在制表符,句号,逗号等的情况下也是如此。

Something like this: 像这样的东西:

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

Although you would probably want to check that there was a match like this: 虽然您可能想要检查是否存在这样的匹配:

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

This splits the string at every word boundary and returns the first one: 这会在每个单词边界处拆分字符串并返回第一个字符串:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM