简体   繁体   中英

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 ?

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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