如何获得子字符串从字符串后最后一次看到的特定字符在javascript
How to get substring from string after last seen to specific characer in javascript?
我想从最后索引匹配空间的字符串中获取子字符串,并将其放入另一个字符串:
例如如果我有: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);
相关文章:
- 如何将字符串拆分为字符,但在javascript中保留空格
- 如何显示字符串中最多 200 个字符
- 我想在Javascript中探索类似C语言的字符串的整个字符
- 如何用jquery替换字符串中可能变化的字符
- 通过跳过拆分字符在 javascript 中拆分字符串
- 使用正则表达式匹配长度为六个字符的字母数字字符串
- 字符串替换-不支持格式字符'}'
- 到UpperCase字符串Javascript中的特定字符索引
- 用类javascript包装span标记中字符串中的字符索引
- 将字符串分组为n个字符的块,并应用替换
- 如何检查一个字符串的所有字符是否都存在于另一个字符串中
- 如何从键Code;中获取字符串/字符值;
- 检查值是否包含字符串字符
- JavaScript字符串字符操作
- 如果数组中的字符串不匹配,请从字符串中删除字符串字符
- Javascript Lingo游戏-字符串字符等于另一个字符串字符
- jQuery替换字符串字符的方法
- Javascript字符串字符检查
- Javascript替换字符串字符
- Javascript的变化与重复(组合)缺失的字符串字符