简体   繁体   English

修剪以特定字符结尾的字符串

[英]trim a string ending with a specific character

for example, I have a variable (var1) with a value of 'root'@'localhost' what's the best way to transform this variable to only root ? 例如,我有一个变量(var1),其值为'root'@'localhost' ,将此变量转换为仅root的最佳方法是什么?

I have tried: 我努力了:

slice(1, var1.length - 13)

But I figure it's not practical since var1 can have a value of 'root'@'%' so what I think I should do is slice the first character " ' " and trim the string starting from the 2nd " ' " so I could get the user name. 但是我认为这是不实际的,因为var1可以具有'root'@'%'的值,所以我认为我应该做的是将第一个字符“ ' “切成薄片并从第二个” ' ”处开始修剪字符串,这样我就可以得到用户名。

Or is there any better way to do it? 还是有更好的方法呢?

In your case you can do something as follows 根据您的情况,您可以执行以下操作

var x = "'root'@admin.com'";  
var y = x.split('@')[0].substr(1).slice(0, -1); 
console.log(y); // output: root

Following is the working fiddle: https://jsfiddle.net/w5Lhou6m/ 以下是有效的小提琴: https : //jsfiddle.net/w5Lhou6m/

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

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