Search code examples
javascriptjqueryspecial-characterstrim

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/


Solution

  • 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)