2

I'm trying to split a string using split() method but it work case-sensitifly, the question is as typed on the title.

The problem is like this

var str, ret;

str = "NubNubLabaLabaNubNub";
ret = str.split("labalaba"); // ret return ["NubNubLabaLabaNubNub"]

// which i wanted ["NubNub","NubNub"]

When i using toLowerCase() or toUpperCase() the whole string will change, and after spliting i want it to be an original one.

str = "NubNubLabaLabaNubNub";
ret = str.toLowerCase().split("labalaba".toLowerCase());

ret return ["nubnub","nubnub"] but the result that i wanted is ["NubNub","NubNub"]

I still not understand how to return the "nubnub" to "NubNub"

Thanks.

Irvan Hilmi
  • 378
  • 1
  • 4
  • 16

1 Answers1

5

You could use a case-insensitive regular expression instead:

const str = "NubNubLabaLabaNubNub";
console.log(
  str.split(/labalaba/i)
);

If the string to split on is in a variable, escape it first, then pass it to new RegExp:

const escape = s => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

const str = "abcfoo()barabc";
const splitOn = 'foo()bar';
const re = new RegExp(escape(splitOn), 'i');
console.log(
  str.split(re)
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • above work fine but how if the split() parameter stored in variable? like `spl = "labalaba"`? and executed like `str.split("/"+spl+"/i")` it seems not working. – Irvan Hilmi Oct 26 '18 at 04:01
  • 1
    See edit, escape the string, then pass it to `new RegExp`. (if there are no special characters in the string, then no need to escape it) – CertainPerformance Oct 26 '18 at 04:04
  • i'm actually have some more question, if the string that i replace incase-sensitifly are `"AsdE"` with `splitOn = "asde"`, how to record the `string` that we repleace are `"AsdE"` not `"asde"` or `"ASDE"`? – Irvan Hilmi Oct 26 '18 at 05:40