简体   繁体   English

提取字符串结尾-Javascript

[英]Extracting end of String - Javascript

Say I have a string 12.13.14 说我有一个字符串12.13.14

How can I get the characters after the last dot. 如何获得最后一个点之后的字符。 (in this case 14)? (在这种情况下为14)?

There can be more than 2 characters. 最多可以包含2个字符。

Examples would be 例子是
34.45.657 34.45.657
10.11.46256 10.11.46256

So after the last dot could be any amount of characters. 因此,最后一个点之后可以是任意数量的字符。

I've messed around with .slice() but can't get anywhere. 我已经把.slice()弄乱了,但是什么都找不到。

You have a bunch of options. 您有很多选择。 One is split and pop : 一个是splitpop

 var str = "12.13.14"; var last = str.split('.').pop(); document.body.innerHTML = last; 

Another is a regular expression 另一个是正则表达式

 var str = "12.13.14"; var match = /\\.([^.]+)$/.exec(str); var last = match && match[1]; document.body.innerHTML = last; 

Or a rex and replace: 或雷克斯并替换:

 var str = "12.13.14"; var last = str.replace(/^.*\\.([^.]+)$/, "$1"); document.body.innerHTML = last; 

Or lastIndexOf and substring , as Ananth shows . lastIndexOfsubstring ,如Ananth所示

var str = '34.45.657';
console.log(str.substring(str.lastIndexOf('.') + 1));

You can do that in multiple ways: 您可以通过多种方式做到这一点:

First way: 第一种方式:

var myString = '12.13.14';
var lastItem = myString.split('.').pop();
console.log(lastItem);

Second Way: 第二种方式:

var myString = '12.13.14';
var lastItem = myString.slice(myString.lastIndexOf('.')+1);
console.log(lastItem);

Third Way: 第三方式:

var myString = '12.13.14';
var lastItem = myString.substring(myString.lastIndexOf('.') + 1);
console.log(lastItem);

and so on ,... 等等 ,...

An easy solution would be to use split() which takes a delimiter. 一个简单的解决方案是使用带有定界符的split()

You could split your string on dots and since split returns an array you could use pop() to get the last result. 您可以将字符串分割为点,由于split返回一个数组,因此可以使用pop()获得最后的结果。

eg 例如

'34.345.3456'.split('.').pop(); // 3456

Easy solution to get your answer like this 简单的解决方案来获得这样的答案

var txt= document.getElementById("Text1").value;
var s1 = txt.lastIndexOf(".");
txt = txt.substring(0, s1); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM