1

Salaam

I am looking for a proper version of a C# or Razor equivalent of PHP's addSlashes. That would add \ to some\string => some\\string

Please provide help

Why I needed this In my application a user entered Sometext in textbox was accidently pressed next time when page when data was populated though Razor it was like this

...append('<span>'+'@Model.value'+'</span>') => after compiling it becomes like this ...append('<span>'+'sometext\'+'</span>')

so with this scenario my javascript code broke at '\' because now single quote has started but not ending due to ``. So i thought instead of limiting characters i would rather add slashes through C# code

Thank You

M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
Ali Jamal
  • 1,383
  • 1
  • 13
  • 20
  • Can you talk us though **why** you want to do this? – mjwills Sep 28 '18 at 06:07
  • Why is this tagged with javascript and regex? – M. Eriksson Sep 28 '18 at 06:18
  • @mjwills Thank You for your response in my application a user entered `Sometext \` in textbox `\` was accidently pressed next time when page when data was populated though Razor it was like this `...append(''+'@Model.value'+'')`=> after compiling it becomes like this `...append(''+'sometext\'+'')` so with this scenario my javascript code broke at `'\'` because now single quote has started but not ending due to `\`. so i thought instead of limiting characters i would rather add slashes through C# code – Ali Jamal Sep 28 '18 at 06:30
  • 2
    @AliJamal Please do not post relevant details of the question in the comments. Edit them to your question, that makes it easier to understand your problem – Kami Kaze Sep 28 '18 at 06:33
  • 1
    I Have tried With This `test / text " '" 12# 2 !@#" @!"#@!"4 @!'4 @!"$"" ?/23 ``'/'\3/[[q//323/54@3/5@#%"@ ?#"` `````""~"~"@~ <> ` String Its Not Working – Ali Jamal Sep 28 '18 at 07:44

1 Answers1

0

You don't show any code you've already written, but this can be done by using [string.replace()] ( https://www.w3schools.com/jsref/jsref_replace.asp ) :

var str = "This is \\a test";
var replaced = str.replace("\\", "\\\\");

Whoops - you want the answer in C# , I misread your "javascript" tag. It's mostly the same:

string str = "This is \\a test";
string replaced = str.Replace("\\", "\\\\");

Also see C# String Replace

After the update, https://stackoverflow.com/a/27574931/34092 is most likely a much better answer.

Corion
  • 3,855
  • 1
  • 17
  • 27