I need to escape double quotes in javascript - javascript

In the example below I run str through .replace and populate the div with id of wtf with the output. The problem is I have to manually escape the double quotes for str.replace to work.
Is there a way to automatically escape the double quotes?
<body>
<div id="wtf"></div>
<script>
var str = ("this string has "double quotes" as well as 'single quotes'..");
var well = str.replace(/\s\d{2}\s(\d{2}\s)?/g,' ');
wtf.innerHTML = well;
</script>
</body>

You must escape the double quotes manually. There's no way to do automatically because the str produce the following error then javascript wouldn't execute further ahead lines of code:

Use the backslash ( \ ) to escape your double quotes.
It should look like this :
var str = ("this string has \"double quotes\" as well as 'single quotes'..");
There's no automatic way to do this.

If you want to replace the quotes, it is best to replace them with their HTML entity. Using a method like this, you can accomplish it.
var tokens = [
['"', '"'],
["'", ''']
];
var clean = [];
for(var i = 0; i < MY_STRING.length; i++) {
var s = MY_STRING[i];
for(var a = 0; a < tokens.length; a++)
if(tokens[a][0] == s) {
s = tokens[a][1];
break;
}
clean.push(s);
}
var cleanString = clean.join("");

Related

Javascript regex to add to every character of a string a backslash

So as the title says I'd like to add to every character of a string a backslash, whether the string has special characters or not. The string should not be considered 'safe'
eg:
let str = 'dj%^3&something';
str = str.replace(x, y);
// str = '\d\j\%\^\3\&\s\o\m\e\t\h\i\n\g'
You could capture every character in the string with (.) and use \\$1 as replacement, I'm not an expert but basically \\ will render to \ and $1 will render to whatever (.) captures.
HIH
EDIT
please refer to Wiktor Stribiżew's comment for an alternative which will require less coding. Changes as follows:
str = str.replace(/(.)/g, '\\$1'); for str = str.replace(/./g, '\\$&');
Also, for future reference I strongly advice you to visit regexr.com when it comes to regular expressions, it's helped ME a lot
let str = 'dj%^3&something';
str = str.replace(/(.)/g, '\\$1');
console.log(str);
If you just want to display a string safely, you should just do:
let str = 'dj%^3&something';
let node = document.createTextNode(str);
let dest = document.querySelector('.whatever');
dest.appendChild(node);
And then you are guaranteed that it will be treated as text, and won't be able to execute a script or anything.
For example: https://jsfiddle.net/s6udj03L/1/
You can split the string to an array, add a \ to each element to the array, then joint the array back to the string that you wanted.
var str = 'dj%^3&something';
var split = str.split(""); // split string into array
for (var i = 0; i < split.length; i++) {
split[i] = '\\' + split[i]; // add backslash to each element in array
}
var joint = split.join('') // joint array to string
console.log(joint);
If you don't care about creating a new string and don't really have to use a regex, why not just iterate over the existing one and place a \ before each char. Notice to you have to put \\ to escape the first \.
To consider it safe, you have to encode it somehow. You could replace typical 'non-safe' characters like in the encode() function below. Notice how & get's replaced by &
let str = 'dj%^3&something';
let out = "";
for(var i = 0; i < str.length; i++) {
out += ("\\" + str[i]);
}
console.log(out);
console.log(encode(out));
function encode(string) {
return String(string).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}

Regular expression to escape double quotes within double quotes

I have a string that needs to be parsed as JSON.
The problem is, it may sometimes contain double quotes, causing errors in parsing.
For example:
{
"id_clients":"58844",
"id_clients_name" : ""100" test"qw"
}
I need a regex to replace any double quotes between the opening and closing " with a \".
Thanks.
I tried it just for fun, even though it is certainly better to fix the generator. This might work in your case, or at least inspire you:
You can try it here
$( function()
{
var myString = "{ \"na\"\"me\": \"va\"lue\", \"tes\"\"t\":\"ok\" }";
var myRegexp = /\s*\"([\w\"]+)\"\s*[,}:]/g;
var match;
var matches = [];
// Save all the matches
while((match = myRegexp.exec(myString)) !== null)
{
matches.push(match[1]);
console.log(match[1]);
}
// Process them
var newString = myString;
for (var i=0; i<matches.length; i++)
{
var newVal = matches[i].replace(/\"/g, '\\\"');
newString = newString.replace(matches[i], newVal);
}
alert(myString + "\n" + newString);
}
);
You can try, although this will work only for the opening tags :
.replace(/\"\"/g, '\\""');

Put quotes around a variable string in JavaScript

I have a JavaScript variable:
var text = "http://example.com"
Text can be multiple links. How can I put '' around the variable string?
I want the strings to, for example, look like this:
"'http://example.com'"
var text = "\"http://example.com\"";
Whatever your text, to wrap it with ", you need to put them and escape inner ones with \. Above will result in:
"http://example.com"
var text = "http://example.com";
text = "'"+text+"'";
Would attach the single quotes (') to the front and the back of the string.
I think, the best and easy way for you, to put value inside quotes is:
JSON.stringify(variable or value)
You can add these single quotes with template literals:
var text = "http://example.com"
var quoteText = `'${text}'`
console.log(quoteText)
Docs are here. Browsers that support template literals listed here.
Try:
var text = "'" + "http://example.com" + "'";
To represent the text below in JavaScript:
"'http://example.com'"
Use:
"\"'http://example.com'\""
Or:
'"\'http://example.com\'"'
Note that: We always need to escape the quote that we are surrounding the string with using \
JS Fiddle: http://jsfiddle.net/efcwG/
General Pointers:
You can use quotes inside a string, as long as they don't match the
quotes surrounding the string:
Example
var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
Or you can put quotes inside a string by using the \ escape
character:
Example
var answer='It\'s alright';
var answer="He is called \"Johnny\"";
Or you can use a combination of both as shown on top.
http://www.w3schools.com/js/js_obj_string.asp
let's think urls = "http://example1.com http://example2.com"
function somefunction(urls){
var urlarray = urls.split(" ");
var text = "\"'" + urlarray[0] + "'\"";
}
output will be text = "'http://example1.com'"
In case of array like
result = [ '2015', '2014', '2013', '2011' ],
it gets tricky if you are using escape sequence like:
result = [ \'2015\', \'2014\', \'2013\', \'2011\' ].
Instead, good way to do it is to wrap the array with single quotes as follows:
result = "'"+result+"'";
You can escape " with \
var text="\"word\"";
http://jsfiddle.net/beKpE/
Lets assume you have a bunch of urls separated by spaces. In this case, you could do this:
function quote(text) {
var urls = text.split(/ /)
for (var i = 0; i < urls.length; i++) urls[i] = "'" + urls[i] + "'"
return urls.join(" ")
}
This function takes a string like "http://example.com http://blarg.test" and returns a string like "'http://example.com' 'http://blarg.test'".
It works very simply: it takes your string of urls, splits it by spaces, surrounds each resulting url with quotes and finally combines all of them back with spaces.
var text = "\"http://www.example1.com\"; \"http://www.example2.com\"";
Using escape sequence of " (quote), you can achieve this
You can place singe quote (') inside double quotes without any issues
Like this
var text = "'http://www.ex.com';'http://www.ex2.com'"
Another easy way to wrap a string is to extend the Javascript String prototype:
String.prototype.quote = function() { return "\"" + this + "\""; };
Use it like this:
var s = "abc";
console.log( "unwrapped: " + s + ", wrapped: " + s.quote() );
and you will see:
unwrapped: abc, wrapped: "abc"
This can be one of several solutions:
var text = "http://example.com";
JSON.stringify(text).replace('\"', '\"\'').replace(/.$/, '\'"')

how to config RegExp when string contains parentheses

I'm sure this is an easy one, but I can't find it on the net.
This code:
var new_html = "foo and bar(arg)";
var bad_string = "bar(arg)";
var regex = new RegExp(bad_string, "igm");
var bad_start = new_html.search(regex);
sets bad_start to -1 (not found). If I remove the (arg), it runs as expected (bad_start == 8). Is there something I can do to make the (very handy) "new Regexp" syntax work, or do I have to find another way? This example is trivial, but in the real app it would be doing global search and replace, so I need the regex and the "g". Or do I?
TIA
Escape the brackets by double back slashes \\. Try this.
var new_html = "foo and bar(arg)";
var bad_string = "bar\\(arg\\)";
var regex = new RegExp(bad_string, "igm");
var bad_start = new_html.search(regex);
Demo
Your RegEx definition string should be:
var bad_string = "bar\\(arg\\)";
Special characters need to be escaped when using RegEx, and because you are building the RegEx in a string you need to escape your escape character :P
http://www.regular-expressions.info/characters.html
You need to escape the special characters contained in string you are creating your Regex from. For example, define this function:
function escapeRegex(string) {
return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
}
And use it to assign the result to your bad_string variable:
let bad_string = "bar(arg)"
bad_string = escapeRegex(bad_string)
// You can now use the string to create the Regex :v:

How to globally replace a forward slash in a JavaScript string?

How to globally replace a forward slash in a JavaScript string?
The following would do but only will replace one occurence:
"string".replace('/', 'ForwardSlash');
For a global replacement, or if you prefer regular expressions, you just have to escape the slash:
"string".replace(/\//g, 'ForwardSlash');
Use a regex literal with the g modifier, and escape the forward slash with a backslash so it doesn't clash with the delimiters.
var str = 'some // slashes', replacement = '';
var replaced = str.replace(/\//g, replacement);
You need to wrap the forward slash to avoid cross browser issues or //commenting out.
str = 'this/that and/if';
var newstr = str.replace(/[/]/g, 'ForwardSlash');
Without using regex (though I would only do this if the search string is user input):
var str = 'Hello/ world/ this has two slashes!';
alert(str.split('/').join(',')); // alerts 'Hello, world, this has two slashes!'
Is this what you want?
'string with / in it'.replace(/\//g, '\\');
This has worked for me in turning "//" into just "/".
str.replace(/\/\//g, '/');
Hi a small correction in the above script..
above script skipping the first character when displaying the output.
function stripSlashes(x)
{
var y = "";
for(i = 0; i < x.length; i++)
{
if(x.charAt(i) == "/")
{
y += "";
}
else
{
y+= x.charAt(i);
}
}
return y;
}
This is Christopher Lincolns idea but with correct code:
function replace(str,find,replace){
if (find){
str = str.toString();
var aStr = str.split(find);
for(var i = 0; i < aStr.length; i++) {
if (i > 0){
str = str + replace + aStr[i];
}else{
str = aStr[i];
}
}
}
return str;
}
Example Usage:
var somevariable = replace('//\\\/\/sdfas/\/\/\\\////','\/sdf','replacethis\');
Javascript global string replacement is unecessarily complicated. This function solves that problem. There is probably a small performance impact, but I'm sure its negligable.
Heres an alternative function, looks much cleaner, but is on average about 25 to 20 percent slower than the above function:
function replace(str,find,replace){
if (find){
str = str.toString().split(find).join(replace);
}
return str;
}
var str = '/questions'; // input: "/questions"
while(str.indexOf('/') != -1){
str = str.replace('/', 'http://stackoverflow.com/');
}
alert(str); // output: "http://stackoverflow.com/questions"
The proposed regex /\//g did not work for me; the rest of the line (//g, replacement);) was commented out.
You can create a RegExp object to make it a bit more readable
str.replace(new RegExp('/'), 'foobar');
If you want to replace all of them add the "g" flag
str.replace(new RegExp('/', 'g'), 'foobar');

Categories

Resources