admin管理员组

文章数量:1410696

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

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

Any ideas?

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./r/gP5gL0/1

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

Any ideas?

Share Improve this question asked Feb 1, 2016 at 16:56 DeseaseSpartaDeseaseSparta 2712 gold badges4 silver badges12 bronze badges 4
  • 2 It should be test = "whatever\\aaaaaa" (two slashes). – georg Commented Feb 1, 2016 at 16:59
  • 1 Add you actual code, so we can se why isn't working – Jorge Campos Commented Feb 1, 2016 at 16:59
  • 1 Seems to work: jsfiddle/vjxtwt2m – sp00m Commented Feb 1, 2016 at 16:59
  • What if I only have aa\bb and not aa\\bb – DeseaseSparta Commented Feb 1, 2016 at 17:00
Add a ment  | 

2 Answers 2

Reset to default 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>

Use this

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

var str = 'whatever\\bbbbzzzzz';
alert(str.split(/[\\|\/]/))

本文标签: javascriptRegex to match forward or backward slashStack Overflow