2

I have a string like this :

whatever/aaazzzzz

and sometimes a string like that :

whatever\bbbbzzzzz

I would like to split the string when I match / or \

The regex I tried seems to work

https://regex101.com/r/gP5gL0/1

When I use it in the fiddle, it works with / but not with \

Any ideas?

DeseaseSparta
  • 271
  • 2
  • 4
  • 12

2 Answers2

3

The issue here is not the regex itself, but the unavoidable fact that JavaScript doesn't implicitly support string literals (i.e. ones where backslashes are interpreted as printed as opposed to denoting an escape sequence. Much more can read here).

Strings derived from any source other than source code are interpreted as literal by default, as demonstrated in this fiddle.

<script>
function splitTheString()
{
  //test = escape("whatever\aaaaaa");
  var test = document.getElementById("strToSplit").value;
  a = test.split(/(\\|\/)/)[0];
  alert(a);
}
</script>
<form>
Split this string:<br>
  <input type="text" id="strToSplit">
  <a href="javascript:splitTheString();">Split the string</a>
</form>
Community
  • 1
  • 1
CJPN
  • 1,497
  • 1
  • 9
  • 8
2

Use this

var arr = str.split(/[\\|\/]/);

var str = 'whatever\\bbbbzzzzz';
alert(str.split(/[\\|\/]/))
Siva
  • 2,735
  • 16
  • 14