Javascript中最简单的子字符串处理方法

Easiest way to sub-string the following strings in Javascript

本文关键字:字符串 处理 方法 最简单 Javascript      更新时间:2023-09-26

字符串看起来像这样:

"Hello John and Hi Anne"

"Hello Daniel and Hi Kraig"

我想从字符串中获取名称;例如

var name1 = "John"
var name2 = "Anne"

"

Hello, Hi, and不会改变,只有名称会改变。

如何在Javascript中执行此操作?我真的不想计数索引

编辑:在name变量中没有空格,即name不能是"John Doe"。

var nameString = "Hello John and Hi Anne";
var names = nameString.match(/Hello (.*) and Hi (.*)/);
console.log(names[1]); // John
console.log(names[2]); // Anne
var array = "Hello Daniel and Hi Kraig".split(' ')
var name1 = array[1]
var name2 = array[array.length - 1]

您可以使用regexp来获取名称。

var string = "Hello John and Hi Anne";
var matches = string.match(/Hello's+([a-zA-Z]+)'s+and's+Hi's+([a-zA-z]+)/);
console.log(matches[1], matches[2]);

's+表示一个或多个白色字符

[a-zA-Z]+表示a-z和a-z中的一个或多个字符

在string:

中使用match方法
var phrase = "Hello John and Hi Anne";
var match = phrase.match("Hello (.*) and Hi (.*)");
console.log(match[1], match[2]);