Reputation: 457
Hi I want to read values before and after special character in text of a variable.
The special character will always be the same e.g., '|' For example, my text will be stored as
var username = Username|Jackie;
var password = Password|myPass;
var temp = ""
After reading the, I would be carrying out a if-statement as follows
IF text BEFORE | == USERNAME
temp == text AFTER |
ESLE IF text BEFORE == Password
temp == text AFTER |
I hope I am making sense, if not, please let me know :)
I have been able to do this, but it only reads text after the special text and I want both after and before.
var myString = someVariableName.val().split("|").pop();
https://jsfiddle.net/bf1L5e7y/1/
Upvotes: 1
Views: 6910
Reputation: 374
.split() will take a string and generate an array around the delimiter you define. (String.prototype.split()) This means that running .split() on your strings will return an array of length 2 with your value in index 1.
const username = "Username|Jackie";
const arr = username.split("|");
console.log(arr); // ["Username", "Jackie"];
const username = "Username|Jackie";
const arr = username.split("|");
console.log(arr); // ["Username", "Jackie"];
console.log(arr[0]); // "Username"
console.log(arr[1]); // "Jackie"
const [type, val] = username.split("|");
console.log(type); // "Username"
console.log(val); // "Jackie"
Upvotes: 1
Reputation: 9451
You can do this in one line using destructuring
A working example
var [before, after] = 'Username|Jackie'.split("|")
console.log(before)
console.log(after)
The above is the same as doing this:
var pieces = 'Username|Jackie'.split("|")
var before = pieces[0]
var after = pieces[1]
console.log(before)
console.log(after)
Upvotes: 2