0

I have a problem with the string symbol error, I want replace this symbol \, but it doesn't work. My sample code javascript like below the coding:

I am doing below this testing, cannot alert the message

var file_name = "C:\fakepath\claim 20210121 1754.sql";
var bbb = file_name.replace("C:\fakepath", "123");
alert(bbb);

If below the javascript code without \ , it can replace, the alert message is 123\fakepath\claim 20210121 1754.sql:

var file_name = "C:\fakepath\claim 20210121 1754.sql";
var bbb = file_name.replace("C:", "123");
alert(bbb);

Actually I want the alert message result is 123\claim 20210121 1754.sql

2
  • 1
    Try file_name.replace("C:\\fakepath", "123"); with 2 backslashes Commented Jan 22, 2021 at 4:41
  • Windows allows you to use forward slashes as directory separators. That will make things easier. Commented Jan 22, 2021 at 4:42

2 Answers 2

2

Backslash begins escape sequences, you need to double them to make them literal.

var file_name = "C:\\fakepath\\claim 20210121 1754.sql";
var bbb = file_name.replace("C:\\fakepath", "123");
alert(bbb);

Sign up to request clarification or add additional context in comments.

Comments

1

Escape the escape character (\) by doubling (\\) it:

const file_name = "C:\fakepath\claim 20210121 1754.sql"
const bbb = file_name.replace("C:\fakepath", "123\\")
const p = document.querySelector('pre')
p.innerText += bbb
<pre></pre>

Output:

123\claim 20210121 1754.sql

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.