1

I know that to split by strings I can use e.g. x.split(/Age:|Date:/g); How split a string in jquery with multiple strings as separator and to split by a character, like : I can use x.split(':');

I need to split a string by the following, if applicable

:
am
AM
pm
PM

Tried both of these but they don't work.

var array = str.split('/:|am|AM|pm|PM/g');
var array = str.split('/\:|am|AM|pm|PM/g');
var array = str.split('/(:|am|AM|pm|PM)/g');

JSFiddle https://jsfiddle.net/dkasce2e/1/

gene b.
  • 10,512
  • 21
  • 115
  • 227

2 Answers2

2

Don't use Quotes while using the regex pattern. Use the following instead

var array = str.split(/:|am|AM|pm|PM/g);

Here is your full example:

function splitTime(str) {

 var array = str.split(/:|am|AM|pm|PM/g);
        console.log("[0]: " + array[0] + " [1]: " + array[1] + " [2]: " + array[2]);

}

splitTime('12:20am');
splitTime('00:20am');
splitTime('4:00PM');
splitTime('14:30am');

RegEx is supported without quotes and typically surrounded by / followed by access flags. In Javascript RegEx is supported in match, replace, search, split functions of String Object. More details can be found in Javascript Regular Expressions Guide in Mozilla

Abhilash Nayak
  • 664
  • 4
  • 10
  • Indeed, its a common mistake people make when using regex patters, some APIs need the pattern to be in quotes(takes as a String) and some as raw regex pattern, like the above api. More details about using RegEx in javascript can be found in this excellent guide. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions – Abhilash Nayak Oct 26 '17 at 16:08
1

Regex doesn't go inside quotation marks in JS. '/myregexpattern/' will look for exactly that string. Use /yourpatternhere/ instead.

Daniel Nielson
  • 381
  • 1
  • 8