Jquery:仅用第一个单词替换字符串

Jquery: Replace string with only the first word

本文关键字:单词 替换 字符串 第一个 Jquery      更新时间:2023-09-26

我到处找都找不到这个…

我有一个字符串,我想用第一个单词替换整个字符串。

例如:

String: "hello world"

新字符串:"hello"

提前感谢!

var s = "hello world"
s = s.replace(/('w+).*/,"$1");

可以了

最快和最简单的方法是根据空格将字符串分成一个数组,然后将其设置为第一个。

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