0

I am sending a string variable from spring boot controller to JavaScript and my string is basically a file path with single backslash. I am reading the path in JavaScript but it is ready single backslash as a escape character or something.

<script type="text/javascript">
    var path = "S:\\CD\2020\ABCDEF"
    alert(path)
</script>

The output I am getting is S:\CD‚0ABCDEF in the alert

I want "S:\CD\2020\ABCDEF"

isherwood
  • 58,414
  • 16
  • 114
  • 157
Mutahir Kiani
  • 83
  • 1
  • 1
  • 11

3 Answers3

1

You need to do

var path = "S:\\CD\\2020\\ABCDEF"

a backslash is an escape character so you need to escape the backslash.

If you don't control it, try to use String.raw like so:

alert(String.raw`S:\\CD\2020\ABCDEF`)
dave
  • 62,300
  • 5
  • 72
  • 93
1

In JavaScript \ is an escape character used to denote the beginning of special sequences.

These sequences include \n, \t and even Unicode characters. When you want to use the \ character on its own, write two like this \\.

So in your case:

  • We can use String.raw to stop JavaScript from parsing escape sequences.
  • And also .replaceAll to change all occurrences of the \\ sequence.

var path = String.raw`S:\\CD\2020\ABCDEF`

let singular = (String.raw`\a`).slice(0, 1)
let double = String.raw`\\`

path = path.replaceAll(double, singular)

alert(path)

As a function:

function getString() {
   return String.raw `S:\\CD\2020\ABCDEF`
} // This function can be replaced with the function you are using to get the path from the user.

function replaceEscapes(rawString) {
  let singular = (String.raw `\a`).slice(0, 1)
  let double = String.raw `\\`

  return rawString.replaceAll(double, singular)
}

alert(
  replaceEscapes(getString())
)
lejlun
  • 4,140
  • 2
  • 15
  • 31
1

\ is used to escape characters. Add an extra \ to get past it:

var path = "S:\\C\\2020\\ABCDEF"
    alert(path)
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39