Does JavaScript have a built-in function like PHP's addslashes (or addcslashes) function to add backslashes to characters that need escaping in a string?
For example, this:
This is a demo string with
'single-quotes' and "double-quotes".
...would become:
This is a demo string with
\'single-quotes\' and
\"double-quotes\".
http://locutus.io/php/strings/addslashes/
function addslashes( str ) {
return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}
You can also try this for the double quotes:
JSON.stringify(sDemoString).slice(1, -1);
JSON.stringify('my string with "quotes"').slice(1, -1);
A variation of the function provided by Paolo Bergantino that works directly on String:
String.prototype.addSlashes = function()
{
//no need to do (str+'') anymore because 'this' can only be a string
return this.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}
By adding the code above in your library you will be able to do:
var test = "hello single ' double \" and slash \\ yippie";
alert(test.addSlashes());
EDIT:
Following suggestions in the comments, whoever is concerned about conflicts amongst JavaScript libraries can add the following code:
if(!String.prototype.addSlashes)
{
String.prototype.addSlashes = function()...
}
else
alert("Warning: String.addSlashes has already been declared elsewhere.");
Use encodeURI()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI
Escapes pretty much all problematic characters in strings for proper JSON encoding and transit for use in web applications. It's not a perfect validation solution but it catches the low-hanging fruit.
You can also use this
let str = "hello single ' double \" and slash \\ yippie";
let escapeStr = escape(str);
document.write("<b>str : </b>"+str);
document.write("<br/><b>escapeStr : </b>"+escapeStr);
document.write("<br/><b>unEscapeStr : </b> "+unescape(escapeStr));
Related
I want to replace the smart quotes like ‘, ’, “ and ” to regular quotes. Also, I wanted to replace the ©, ® and ™. I used the following code. But it doesn't help.
Kindly help me to resolve this issue.
str.replace(/[“”]/g, '"');
str.replace(/[‘’]/g, "'");
Use:
str = str.replace(/[“”]/g, '"');
str = str.replace(/[‘’]/g, "'");
or to do it in one statement:
str = str.replace(/[“”]/g, '"').replace(/[‘’]/g,"'");
In JavaScript (as in many other languages) strings are immutable - string "replacement" methods actually just return the new string instead of modifying the string in place.
The MDN JavaScript reference entry for replace states:
Returns a new string with some or all matches of a pattern replaced by a replacement.
…
This method does not change the String object it is called on. It simply returns a new string.
replace return the resulting string
str = str.replace(/["']/, '');
The OP doesn't say why it isn't working, but there seems to be problems related to the encoding of the file. If I have an ANSI encoded file and I do:
var s = "“This is a test” ‘Another test’";
s = s.replace(/[“”]/g, '"').replace(/[‘’]/g,"'");
document.writeln(s);
I get:
"This is a test" "Another test"
I converted the encoding to UTF-8, fixed the smart quotes (which broke when I changed encoding), then converted back to ANSI and the problem went away.
Note that when I copied and pasted the double and single smart quotes off this page into my test document (ANSI encoded) and ran this code:
var s = "“This is a test” ‘Another test’";
for (var i = 0; i < s.length; i++) {
document.writeln(s.charAt(i) + '=' + s.charCodeAt(i));
}
I discovered that all the smart quotes showed up as ? = 63.
So, to the OP, determine where the smart quotes are originating and make sure they are the character codes you expect them to be. If they are not, consider changing the encoding of the source so they arrive as “ = 8220, ” = 8221, ‘ = 8216 and ’ = 8217. Use my loop to examine the source, if the smart quotes are showing up with any charCodeAt() values other than those I've listed, replace() will not work as written.
To replace all regular quotes with smart quotes, I am using a similar function. You must specify the CharCode as some different computers/browsers default settings may identify the plain characters differently ("",",',').
Using the CharCode with call the ASCII character, which will eliminate the room for error across different browsers, and operating systems. This is also helpful for bilingual use (accents, etc.).
To replace smart quotes with SINGLE QUOTES
function unSmartQuotify(n){
var name = n;
var apos = String.fromCharCode(39);
while (n.indexOf("'") > -1)
name = name.replace("'" , apos);
return name;
}
To find the other ASCII values you may need. Check here.
var str='\E\\E\10.1.2.154\E\bcs\E\30877_P9999_Adult{2}_02_05_2019_0329p.pdf';
var res=str.replace('\E', '');
I am getting return like this:
\E.1.2.154EcsE877_P9999_Adult{2}_02_05_2019_0329p.pdf
I need to replace all '\E' from string and expecting output like this (\\10.1.2.154\bcs\30877_P9999_Adult{2}_02_05_2019_0329p.pdf). Some body please advise on this . I tried to do several way to fix this. No luck. When I tried with C# it's working fine.
static void Main(string[] args)
{
string str=#"\E\\E\10.1.2.154\E\bcs\E\30877_P9999_Adult{2}_02_05_2019_0329p.pdf";
str=str.Replace(#"\E","");
Console.WriteLine(str);
Console.Read();
}
But, I need it in JavaScript.
var str='\E\\E\10.1.2.154\E\bcs\E\30877_P9999_Adult{2}_02_05_2019_0329p.pdf';
var res=str.replace(/\\E/g, '');
console.log(str, res)
You must use RegExg to eliminate the escape inside a string in JavaScript.
In JavaScript the equivalent of the C# # prefix is String.raw followed by a template literal (notice the backtics).
And to replace all occurrences, not just one, you need to pass a regex to replace with g modifier.
var str=String.raw`\E\\E\10.1.2.154\E\bcs\E\30877_P9999_Adult{2}_02_05_2019_0329p.pdf`;
var res=str.replace(/\\E/g, '');
console.log(res);
NB: The backslash in a regular expression is an escape character, so you need \\ for one literal backslash.
If for some reason you really want to avoid the use of a regex, then there is the split/join trick, but it is a bit slower:
var str=String.raw`\E\\E\10.1.2.154\E\bcs\E\30877_P9999_Adult{2}_02_05_2019_0329p.pdf`;
var res=str.split(String.raw`\E`).join('');
console.log(res);
Older JS engines
For older JS engines that do not support String.raw you need to use standard string literals, which use the backslash as escape character. So then you need to double all of them. But this is only needed when you write the string as a literal. When you get the string via some API, then there is no need to alter the string before doing the replacement:
var str='\\E\\\\E\\10.1.2.154\\E\\bcs\\E\\30877_P9999_Adult{2}_02_05_2019_0329p.pdf';
var res=str.replace(/\\E/g, '');
console.log(res);
I am trying to replace the string below with whitespaces using javascript
function replaceString()
{
var str = "ABC**EFG";
return str.replace(/\*/g, " ");
}
I received the result as ABC EFG but I expect the result to come with two whitespace.
I also tried the same thing using php str.replace but still get the same result.
Is there any other methods i can used to replace the individual asterisk with whitespace??
P/S: The return string will be used as part of the sql query
[UPDATE]
I ended up return the string without any replacement to sql, then I use sql replace function to perform replacement in the query.
If you're displaying the resulting string in an HTML element then two or more whitespaces will be displayed as only one whitespace. To workaround this fact, use instead:
return str.replace(/\*/g, ' ');
try this
return str.replace(/\*/g, ' ');
Buddy the problem is with the HTML compiler which has its own special rules of parsing
So it parses multiple spaces into one.This can work for HTML only.
Thats why use the GIFT tag .
<pre>
<p id="para"></p>
</pre>
<script> function replaceString()
{
var str = "ABC**EFG";
return str.replace(/\*/g," ");
}
document.getElementById("para").innerHTML=replaceString();
</script>
<script>
function replaceString()
{ var str1=String.fromCharCode(32,32);
var str = "ABC**EFG";
return str.replace(/\*/g,str1);
}
alert(replaceString());
</script>
return of function from above code can be used directly in mysql...
Finally found the best solution, I replace those special characters using percent-encoding (URL-encoding)
for my case: str.replace(/\*/g, "%20");
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"
I have a string that will look something like this:
I'm sorry the code "codehere" is not valid
I need to get the value inside the quotes inside the string. So essentially I need to get the codehere and store it in a variable.
After some researching it looks like I could loop through the string and use .charAt(i) to find the quotes and then pull the string out one character at a time in between the quotes.
However I feel there has to be a simpler solution for this out there. Any input would be appreciated. Thanks!
You could use indexOf and lastIndexOf to get the position of the quotes:
var openQuote = myString.indexOf('"'),
closeQuote = myString.lastIndexOf('"');
Then you can validate they are not the same position, and use substring to retrieve the code:
var code = myString.substring(openQuote, closeQuote + 1);
Regex:
var a = "I'm sorry the code \"codehere\" is not valid";
var m = a.match(/"[^"]*"/ig);
alert(m[0]);
Try this:
var str = "I'm sorry the code \"cod\"eh\"ere\" is not valid";
alert(str.replace(/^[^"]*"(.*)".*$/g, "$1"));
You could use Javascript's match function. It takes as parameter, a regular expression. Eg:
/\".*\"/
Use regular expressions! You can find a match using a simple regular expressions like /"(.+)"/ with the Javascript RegExp() object. Fore more info see w3schools.com.
Try this:
var msg = "I'm sorry the code \"codehere\" is not valid";
var matchedContent = msg.match(/\".*\"/ig);
//matchedContent is an array
alert(matchedContent[0]);
You should use a Regular Expression. This is a text pattern matcher that is built into the javascript language. Regular expressions look like this: /thing to match/flags* for example, /"(.*)"/, which matches everything between a set of quotes.
Beware, regular expressions are limited -- they can't match nested things, so if the value inside quotes contains quotes itself, you'll end up with a big ugly mess.
*: or new RegExp(...), but use the literal syntax; it's better.
You could always use the .split() string function:
var mystring = 'I\'m sorry the code "codehere" is not valid' ;
var tokens = [] ;
var strsplit = mystring.split('\"') ;
for(var i=0;i<strsplit.length;i++) {
if((i % 2)==0) continue; // Ignore strings outside the quotes
tokens.push(strsplit[i]) ; // Store strings inside quotes.
}
// Output:
// tokens[0] = 'codehere' ;