在空格前获取一些字符串,并使用 Javascript 将其保存在变量中

Mat*_*hew 2 html javascript

如何从字符串“John Smith”中获取“John”?

(我不想使用 .substring(); 因为它在联系表单上并且值可能会有所不同。)

基本上我需要在第一个空间之前得到所有东西。;)

   <h1 id="name">John Smith</h1>

<script>

    var str = document.getElementById("name");

    var first = str.split(" ")[0];

    alert(first);

</script>
Run Code Online (Sandbox Code Playgroud)

tek*_*agi 6

您可以使用该String.split方法。

"John Smith".split(" ")[0] 将返回“约翰”

在您的情况下,它将是:

var str = document.getElementById("name").innerHTML;
var first = str.split(" ")[0];
alert(first);
Run Code Online (Sandbox Code Playgroud)