0

I'm trying to get the username from a JSON property I get returned from Sharepoint's restful API.

The property/string I receive: "i:0#.w|xyz\tzzjjaa"

What I want: "xyz\tzzjjaa"

I tried: "i:0#.w|xyz\tzzjjaa".replace("\\","\\\\"), which returns: "i:0#.w|corproot tzzjjaa"

Why is this the case? (is the backslash kind of escaping the "t" in the string?) How can I fix it to just get "xyz\tzzjjaa"?

Thanks alot. :)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
sandrooco
  • 8,016
  • 9
  • 48
  • 86

4 Answers4

2
var str = String.raw`i:0#.w|xyz\tzzjjaa`;
console.log(str.split("|")[1]);

Assuming you want to keep the backslash see a really good answer by T.J. Crowder on using the String.raw function, then split the string on the pipe and take the second part of the resulting array.

Demo: https://jsfiddle.net/snjfveo6/

If you don't want the backslash you can remove the String.raw part and skip to splitting the string.

Community
  • 1
  • 1
Jonathan Newton
  • 832
  • 6
  • 18
0
var str = "i:0#.w|xyz\tzzjjaa".replace("i:0#.w|", "");
alert(JSON.stringify(str));

Demo

Sathvik Chinnu
  • 565
  • 1
  • 7
  • 23
-1

are you sure it should be "tzzjjaa"? \t in a quoted string literal (or in the JSON string) is not \ followed by t, it represents a TAB (ASCII Code# 09) character instead!

some1
  • 857
  • 5
  • 11
  • @Sandrooco if it is a \ followed by t, then it should be coded as `"i:0#.w|xyz\\tzzjjaa"`, or with the `String.raw` as suggested above. instead of splitting the string, you may still use the replace function in the following manner: `.replace(/^.+\|/,"")` – some1 Aug 23 '16 at 01:58
-1

\t in a JS-string is escaped to a Tab-character.

Your best solution as I see it, is to escape it on the server-side.

In your case you will have to write a little server-script, that calls your used API and converts/escapes everything to be ready for your JS. And your JS calls this little server-script.

If your username is sure to never start with an x after the backslash, then:

Either go with JNewtons's answer and use the String.raw-method, or for wider support use the Stringify-method by Sathvik Cheela.

But if there is a chance that it might start with an x after the backslash, you have currently no way to solve this in the Frontend in JavaScript – only in a backend.

Community
  • 1
  • 1
Sebastian G. Marinescu
  • 2,374
  • 1
  • 22
  • 33