How to replace "\" with "\\" from a string using Javascript? - javascript

I tried mystring.replace(/\\/g,"\\") but that didn't work.
Can someone advise me how to do this replacement?
Example: String = "C:\Users\Test\FileName"
When I replace \ with \\, I need to see a result as follows:
C:\\Users\\Test\\FileName

Inside string \-backslash is used to escape the following character. In the string, "C:\Users\Test\FileName" also backslash is used as escape sequence and actual string is "C:UsersTestFileName"
var str = "C:\Users\Test\FileName";
console.log(str);
To make this correct, the backslashes in the string should already escaped.
var str = "C:\\Users\\Test\\FileName";
var str = "C:\\Users\\Test\\FileName";
console.log(str);
The regex can now be used to double the backslashes
str.replace(/\\/g, '\\\\');
var str = "C:\\Users\\Test\\FileName";
console.log(str);
console.log(str.replace(/\\/g, '\\\\'));

Try this, use raw string,String.raw() method is a tag function of template literals
String.raw`\"`.replace(/\"/g, '\\"');
or,if first one isn't work,try this :) hope this will be helped to you
String.raw\".replace(/\\"/g, '\\"');

Related

JavaScript String replace() Method not working for NewsAPI http response text [duplicate]

I am trying to replace curly quotes:
str = '“I don’t know what you mean by ‘glory,’ ” Alice said.';
Using:
str.replace(/['"]/g,'');
Why it does not work? How can I do this?
You might have to (or prefer to) use Unicode escapes:
var goodQuotes = badQuotes.replace(/[\u2018\u2019]/g, "'");
That's for funny single quotes; the codes for double quotes are 201C and 201D.
edit — thus to completely replace all the fancy quotes:
var goodQuotes = badQuotes
.replace(/[\u2018\u2019]/g, "'")
.replace(/[\u201C\u201D]/g, '"');
It doesn't work because you're trying to replace the ASCII apostrophe (or single-quote) and quote characters with the empty string, when what's actually in your source string aren't ASCII characters.
str.replace(/[“”‘’]/g,'');
works.
Combining Pointy and Wooble's answers, if you want to replace the curly quotes with regular quotes:
str = str.replace(/[“”]/g, '"').replace(/[‘’]/g, "'");
So for example:
str = '“I don’t know what you mean by ‘glory,’ ” Alice said.';
str = str.replace(/[“”]/g, '"').replace(/[‘’]/g, "'");
console.log(str)

String.replace with special characters noting working

I have spent several hours trying to figure out what is going on here looking at stack overflow and elsewhere and I cannot figure out what is going on. I would really appreciate any help!!
I need to make document.write('< /div>'); go to -> < /div>
I've simplified it down to the simplest possible case with the html example below.
<script>
var str = "document.write('</div>');";
str = str.replace("/document.write/g","");
console.log(str); //</div>
</script>
Exclude the quotes and it works. It is being interpreted as a string literal because of the quotes, whereas a regular expression literal is expressed between plain /s.
Also, . needs to be escaped or it matches any other single character.
<script>
var str = "document.write('</div>');";
str = str.replace(/document\.write/g,"");
console.log(str); //</div>
</script>
String.prototype.replace() accepts either a string or a regex. If you are going with a string this should be:
var str = "document.write('</div>');";
str = str.replace("document.write","");
console.log(str);

How to replace all the \ from a string with space in javascript?

For example:
var str="abc\'defgh\'123";
I want to remove all the \ using Javascript. I have tried with several functions but still can't replace all the forward slashes.
I've posted a huuuge load of bollocks on JS and multiple replace functionality here. But in your case any of the following ways will do nicely:
str = str.replace('\\',' ');//Only replaces first occurrence
str = str.replace(/\\/g,' ');
str = str.split('\\').join(' ');
As #Guillaume Poussel pointed out, the first approach only replaces one occurrence of the backslash. Don't use that one, either use the regex, or (if your string is quite long) use the split().join() approach.
Just use the replace function like this:
str = str.replace('\\', ' ');
Careful, you need to escape \ with another \. The function returns the modified string, it doesn't modify the string on which it is called, so you need to catch the return value like in my example! So just doing:
str.replace('\\', ' ');
And then using str, will work with the original string, without the replacements.
str="abc\\'asdf\\asdf"
str=str.replace(/\\/g,' ')
You want to replace all '\' in your case, however, the function replace will only do replacing once if you use '\' directly. You have to write the pattern as a regular expression.
See http://www.w3schools.com/jsref/jsref_replace.asp.
Try:
string.replace(searchvalue,newvalue)
In your case:
str.replace('\\', ' ');
Using string.replace:
var result = str.replace('\\', ' ');
Result:
"abc 'defgh '123"

How to replace an apostrophe in a string in Javascript?

Given a string in Javacript, such as
var str = "this's kelly";
I want to replace the apostrophe (') with another character. Here is what I've tried so far:
str.replace('"', 'A');
str.replace('\'', 'A');
None of these work.
How do I do it?
Can you also please advices me with the invalid characters that when passed to the query string or URL crashes the page or produces undesired results ? e.g passing apostrophe (') produces undesired result are their any more of them.
var str = "this's kelly"
str = str.replace(/'/g, 'A');
The reason your version wasn't working is because str.replace returns the new string, without updating in place.
I've also updated it to use the regular expression version of str.replace, which when combined with the g option replaces all instances, not just the first. If you actually wanted it to just replace the first, either remove the g or do str = str.replace("'", 'A');
Do this:
str = str.replace("'","A");
str = str.replace("'", "A");
Your running the function but not assigning it to anything again so the var remains unchanged

How to add single quote in the variable in Javascript?

I have variable var str as following:
var str = <option value="1">tea</option>;
I would like to make it as below
var quote_str = '<option value="1">tea</option>;'
Is there anyone can help me? Thanks in advance!
Edit:
I have tried the following code,however, it's not correct.
var quote_str = 'str';
I think that you want the semicolon outside the string literal:
var quote_str = '<option value="1">tea</option>';
If you mean that you want apostrophe characters inside the string also, you can use \' to put an apostrophe in a string delimited by apostrophes:
var quote_str = '\'<option value="1">tea</option>\'';
You can also use quotation marks to delimit the string. Then you don't have to escape the apostrophes, but you have to escape the quotation marks:
var quote_str = "'<option value=\"1\">tea</option>'";
If you already have a string, and want to add apostrophes around it, you concatenate strings:
var quote_str = "'" + str + "'";
Escape each single quote with a back-slash:
var quote_str = '\'<option value="1">tea</option>;\''
…or wrap the string in quotes of a different kind (i.e. double quotes), but be sure to escape the inner double quotes as to not unintentionally close the string:
var quote_str = "'<option value=\"1\">tea</option>;'"
late update: now we have template literals, so the whole thing becomes a breeze:
var quote_str = `'<option value="1">tea</option>;'`
You can escape characters in Javascript with the \. If that's your issue
We can use the backslash () escape character to prevent JavaScript from interpreting a quote as the end of the string.
The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.
Using this method, we can use apostrophes in strings built with ".
'We\'re safely using an apostrophe in single quotes.' We can also use quotation marks in strings built with ".
"Then he said, \"Hello, World!\"";
In my case, i'm unable to use the notation of ${} in rendered Javascript inside Python Mako Templates as it's already using ${} for rendering variables in Mako:
# mako template somewhere
var quote_str = `'${str}'`;
So i just wrote a small function:
# app.js ( a real Javascript file )
function singlequote(text) {
return `'${text}'`;
}
And then I use:
# mako template somewhere
var quote_str = singlequote(str);
# So i'm able to also use something like:
let btn = '<button type="button" onclick="update(' + singlequote(myid) + "," + singlequote(mystate) + ')"> Update </button>';

Categories

Resources