简体   繁体   中英

Jquery: Replace string with only the first word

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!

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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