Jackie
Jackie

Reputation: 457

Get value from a string before and after a special character - Jquery

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

Answers (2)

Nick Abbott
Nick Abbott

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"];
You can access these values using index based array manipulation or the array destructuring notation. (Array Destructuring)

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

Kevin Jantzer
Kevin Jantzer

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

Related Questions