Get the string before the character or another string in JavaScript

  • Use the split() method.
  • Refer to its first [0] element.
variable.split('character or string')[0];

Example:

<script>
   var myString = 'Dog|Max';
   var stringBefore = myString.split('|')[0];

   console.log(stringBefore);
</script>

Output (console): Dog

Example 2:

<script>
   var age = 'Anna is 32 years old.';
   var name = age.split(' is')[0];

   console.log(name);
</script>

Output (console): Anna