最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery: Replace string with only the first word - Stack Overflow

programmeradmin4浏览0评论

I have been looking everywhere and can't find this..

I got a string and I want to replace the whole string with only the first word.

for example:

String: "hello world"

New String: "hello"

Thanks in advance!

I have been looking everywhere and can't find this..

I got a string and I want to replace the whole string with only the first word.

for example:

String: "hello world"

New String: "hello"

Thanks in advance!

Share Improve this question edited Oct 24, 2011 at 18:58 Michael Low 24.5k17 gold badges85 silver badges119 bronze badges asked Oct 24, 2011 at 18:51 GermanManGermanMan 1031 silver badge11 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 6
var s = "hello world"
s = s.replace(/(\w+).*/,"$1");

that'll do it.

The quickest and easiest way is to split the string into an array based on spaces, then set it to be the first one.

var theString = "hello world";
theString = theString.split(" ")[0];
alert(theString); // alerts "hello"
发布评论

评论列表(0)

  1. 暂无评论