如何获得子字符串从字符串后最后一次看到的特定字符在javascript

How to get substring from string after last seen to specific characer in javascript?

本文关键字:字符串 字符 javascript 何获得 最后一次      更新时间:2023-09-26

我想从最后索引匹配空间的字符串中获取子字符串,并将其放入另一个字符串:

例如

如果我有:var string1="hello any body from me";

在string1中我有4个空格,我想在string1中得到最后一个空格后的单词,所以这里我想得到单词"me"…我不知道string1中的空格数…那么我如何从最后一次看到的字符串得到子字符串到特定的字符,比如空格?

您可以使用split方法尝试这样做,其中input是您的字符串:

var splitted = input.split(' ');
var s = splitted[splitted.length-1];

var splitted = "hello any body from me".split(' ');
var s = splitted[splitted.length-1];
console.log(s);

使用split将其创建为数组并获取最后一个元素:

var arr = st.split(" "); // where string1 is st
var result = arr[arr.length-1];
console.log(result);

或者直接:

var string1 = "hello any body from me";
var result = string1.split(" ").reverse()[0];
console.log(result); // me

感谢反向方法

我将使用正则表达式来避免数组开销:

var string1 = "hello any body from me";
var matches = /'s('S*)$/.exec(string1);
if (matches)
    console.log(matches[1]);

您可以使用split方法通过给定的分隔符(在本例中为" ")分隔字符串,然后获得返回数组的最终子字符串。

这是一个很好的方法,如果你想使用字符串的其他部分,它也很容易阅读:

// setup your string
var string1 = "hello any body from me";
// split your string into an array of substrings with the " " separator
var splitString = string1.split(" ");
// get the last substring from the array
var lastSubstr = splitString[splitString.length - 1];
// this will log "me"
console.log(lastSubstr);
// ...
// oh i now actually also need the first part of the string
// i still have my splitString variable so i can use this again!
// this will log "hello"
console.log(splitString[0]);

这是一个很好的方法,如果您喜欢编写快速和肮脏的子字符串,则不需要其余的子字符串:

// setup your string
var string1 = "hello any body from me";
// split your string into an array of substrings with the " " separator, reverse it, and then select the first substring
var lastSubstr = string1.split(" ").reverse()[0];
// this will log "me"
console.log(lastSubstr);