如何从字符串“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)
您可以使用该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)
| 归档时间: |
|
| 查看次数: |
5850 次 |
| 最近记录: |