Reputation: 123
I would need to write a js function that would do this to me:
export const LOGIN_REQUEST = 'app/LoginPage/LOGIN_REQUEST';
Normally it will be:
console.log(LOGIN_REQUEST); // app/LoginPage/LOGIN_REQUEST
And I would need:
app/LoginPage/LOGIN
I would like to cut the string to the first one I encountered _
. How to do it using js?
Upvotes: 1
Views: 35
Reputation: 689
In Javascript, you can use the split
function.
var data = "app/LoginPage/LOGIN_REQUEST".split("_");
console.log(data[0]); // app/LoginPage/LOGIN
Upvotes: 0
Reputation: 28404
You get the index of this character using indexOf
method, and then take the substring before its first occurrence using the substring
method as follows:
let LOGIN_REQUEST = 'app/LoginPage/LOGIN_REQUEST';
let i = LOGIN_REQUEST.indexOf('_');
let str = (i==-1) ? LOGIN_REQUEST : LOGIN_REQUEST.substring(0,i);
console.log(str);
Upvotes: 0
Reputation: 167
LOGIN_REQUEST.split('_')[0]
Splits LOGIN_REQUEST into an array of strings, divided by _
, and returns the first element of the Array. So, everything up to the first _
.
More fully:
const LOGIN_REQUEST = 'app/LoginPage/LOGIN_REQUEST';
console.log(LOGIN_REQUEST.split(`_`)) // ['app/LoginPage/LOGIN', 'REQUEST']
console.log(LOGIN_REQUEST.split(`_`)[0]) // 'app/LoginPage/LOGIN'
Upvotes: 1