Wrap a given input string in double quotes if not already wrapped - javascript

Background
I need to wrap a JavaScript string in double quotes BUT only if the input string is not already wrapped in double quotes. For this question's purposes "wrapped" is considered as beginning and ending in a double quote regardless of grammar rules.
The Question
What's the best way (regex?) to wrap any input string (empty string included) in double quotes while avoiding duplicate wrapping? Solution should handle internal quotes assuming they are already escaped.
Example inputs/results:
Input:
Hello world
Result:
"Hello world"
Input:
"Hello world"
Result:
"Hello world"
Input:
A quick example says \"hello world\"
Result:
"A quick example says \"hello world\""
Input:
*empty string*
Result:
""
Input:
"Hi," he said, "How are you?"
Result: (considered "wrapped"):
"Hi," he said, "How are you?"

A short and simple way is just to test the first and last characters:
var input = // whatever
var wrapped = input;
if ('"' === wrapped || !('"' === wrapped[0] && '"' === wrapped.slice(-1)))
wrapped = '"' + wrapped + '"';
(This works even on empty strings, because ''[0] is undefined and ''.slice(-1) is '', neither of which cause a problem in the if condition.)
You don't say what to do if the input is just a single double-quote character, but I've assumed for the input '"' the output will be '"""'. If that's not what you want obviously you can modify the code above.

I would avoid using a regex. I'll assume from your examples and comments that the following preconditions hold:
internal quotes, if present, are already escaped
the string is either properly wrapped in (unescaped) double quotes or there are no unescaped double quotes (that is, there is never an unescaped double quote at one end and not the other)
If those assumptions are valid, the problem is much simpler. Just test whether the string starts with a double quote (which perforce wouldn't be escaped, since it's the first character) and whether it ends with an unescaped double quote. If only one is missing, you have a string that doesn't conform to the input assumptions. If both are missing, wrap the string; if neither is missing, the string is already wrapped.
Besides checking for an empty string, you also have to check for a string that consists entirely of one double quote.

You guessed it right. The best bay would be to use regex to wrap your string around quotes. Something like below:-
function quoteMe() {
var inpStr = document.getElementById("input");
inpStr.value = '"' + inpStr.value.replace(/"/g, '') + '"'
document.getElementById("result").innerHTML = inpStr.value;
}
<input type="text" value="" id="input" />
<input type="button" value="Quote Me!" onclick="javascript:quoteMe();">
<div id="result">
</div>
;

I would first take the string and replace double quotes then just add.
var res = str.replace('"', '');
res = '"' + res + '"'

Related

Javascript (Regex): How do i replace (Backslash + Double Quote) pairs?

In Javascript, i want the below original string:
I want to replace \"this\" and \"that\" words, but NOT the one "here"
.. to become like:
I want to replace ^this^ and ^that^ words, but NOT the one "here"
I tried something like:
var str = 'I want to replace \"this\" and \"that\" words, but NOT the one "here"';
str = str.replace(/\"/g,"^");
console.log( str );
Demo: JSFiddle here.
But still .. the output is:
I want to replace ^this^ and ^that^ words, but NOT the one ^here^
Which means i wanted to replace only the \" occurrences but NOT the " alone. But i cannot.
Please help.
As #adeneo's comment, your string was created wrong and not exactly like your expectation. Please try this:
var str = 'I want to replace \\"this\\" and \\"that\\" words, but not the one "here"';
str = str.replace(/\\\"/g,"^");
console.log(str);
You can use RegExp /(")/, String.prototype.lastIndexOf(), String.prototype.slice() to check if matched character is last or second to last match in input string. If true, return original match, else replace match with "^" character.
var str = `I want to replace \"this\" and \"that\" words, but NOT the one "here"`;
var res = str.replace(/(")/g, function(match, _, index) {
return index === str.lastIndexOf(match)
|| index === str.slice(0, str.lastIndexOf(match) -1)
.lastIndexOf(match)
? match
: "^"
});
console.log(res);
The problem with String.prototype.replace is that it only replaces the first occurrence without Regular Expression. To fix this, you need to add a g and the end of the RegEx, like so:
var mod = str => str.replace(/\\\"/g,'^');
mod('I want to replace \\"this\\" and \\"that\\" words, but NOT the one "here"');
A less effective but easier to understand to do what you wanted is to split the string with the delimiter and then join it with the replacement, like so:
var mod = str => str.split('\\"').join('^');
mod('I want to replace \\"this\\" and \\"that\\" words, but NOT the one "here"');
Note: You can wrap a string with either ' or ". Suppose your string contains ", i.e. a"a, you will need to put an \ in front of the " as "a"a" causes syntax error. 'a"a' won't cause syntax error as the parser knows the " is part of the string, but when you put a \ in front of " or any other special characters, it means the following character is a special character. So 'a\"a' === 'a"a' === "a\"a". If you want to store \, you will need to use \ regardless of the type of quote you use, so to store \", you will need to use '\\"', '\\\"' or "\\\"".

How to use '' in javascript inside another '' statement?

I have a problem.
I am using a javascript that call the HTML elements and now i want to add another element that also uses javascript but i dont know how to combine them.
This is the first:
list_options+='<li><input type="checkbox" value="Fuction 1 [first]" name="html_options[]" class="check-opt" data="1">Function 1 <span>[first]</span</li>';
The secound js i need to integrate into the first:
<p>Coockie warning, <a onmouseover="nhpup.popup(' Coockie stuff text ');" style="cursor:pointer;" > read more </a>!</p>
So now if i want to combine the to like this it does not work becuse of the '' in the document:
list_options+='<li><input type="checkbox" value="Function 1 [1$]" name="html_options[]" class="check-opt" data="1">Function 1 <span>[1$]</span><p><a onmouseover="nhpup.popup(' TEXT THAT SHOULD GET DISPLAYED ');" style="cursor:pointer;" > ? </a>!</p></li>';
What should i do?
You can escape the single quote with a backslash \ character.
First off: when I refer to String literals I am referring to the creation of string primitives, as shown below. There are two types of strings, primitives and objects. String objects are created like new String(..).
In javascript, string literals are created with quotation marks, or double quotation marks. This means you can define a string like
str = 'a string'
or
str = "a string"
Single Quotation mark
But say you define your string with a quotation mark, like the first example, and you put the word "can't" in it. Now the definition will look like below.
str = 'this can't work'
This will cause an error, because the actual string is considered to be 'this can'. If we want to use quotation marks in a string literal defined with quotation marks, we must escape those characters, with the escape character \ before them. (NOTE: this escape character isn't displayed in the final string, or even in it, as Felix points out in the comments, and is explained in more detail below)
To get the string to actually work and print 'this can't work', this means we would have to do something like this:
str = 'this can\'t not work'
Double Quotation mark
If we define your string with a double quotation mark, like the second example, we can put quotation marks in them without having to escape it, so the following works:
str = "this can't not work"
Now, say we wanted to put a quote into the string. We can use either single or double quotation marks. If we use double quotation marks in a string literal defined with double quotation marks, we will have to escape those characters like when we used single quotation marks in a string literal defined with a single quotation mark, like so:
str = "he said \"foo bar baz\""
If you define you string literal in a single quotation mark, you don't need to escape double quotation marks within that string, like so:
str = 'he said "foo bar baz"'
programmatically creating strings
Say we have a variable that can be true or false and we want to tell a user. to do this, we can create a string variable, and add the value straight into it, like so:
var someValue = true;
var str = 'hey some value is ' + someValue + '.'
You can add to the string as much as you want or like.
Original question
It seems like you want to embed some variable into your string list_options. To do this, try something like below:
list_options+='<li><input type="checkbox" value="Function 1 [1$]" name="html_options[]" class="check-opt" data="1">Function 1 <span>[1$]</span><p><a onmouseover="nhpup.popup(' + SOME_VARIABLE_YOU_WANT_TO_DISPLAY + ');" style="cursor:pointer;" > ? </a>!</p></li>';
If however, you don't want to embed a variable into the string, and want to just display fixed text, try either of the following:
This uses escaped characters:
list_options+='<li><input type="checkbox" value="Function 1 [1$]" name="html_options[]" class="check-opt" data="1">Function 1 <span>[1$]</span><p><a onmouseover="nhpup.popup(\' TEXT THAT SHOULD GET DISPLAYED \');" style="cursor:pointer;" > ? </a>!</p></li>';
This uses double quotation marks:
list_options+='<li><input type="checkbox" value="Function 1 [1$]" name="html_options[]" class="check-opt" data="1">Function 1 <span>[1$]</span><p><a onmouseover="nhpup.popup(" TEXT THAT SHOULD GET DISPLAYED ");" style="cursor:pointer;" > ? </a>!</p></li>';
Escaping Characters
So, escaping characters is something you will need to learn to use when defining your strings, as some characters in strings can break the string creation. Also, there are special characters which do things in a string which you may want, like a new line(use \n), or tab character(use \t). If you want to read more about these characters, just google 'javascript escape characters', or alternatively, MDN has great documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

Splitting string by {0}, {1}...{n} and replace with empty string

I have the following String:
var text = "Hello world! My name is {0}. How {1} can you be?"
I wanna find each of the {n} and replace them with an empty string. I'm totally useless with regex and tried this:
text = text.split("/^\{\d+\}$/").join("");
I'm sure this is an easy answer and probably exist some answer already on SO but I'm not sure what to search for. Not even sure what the "{" are called in english.
Please (if possible) maintain the use of "split" and "join".
Thanks!
You could achieve this through string.replace function.
string.replace(/\{\d+\}/g, "")
Example:
> var text = "Hello world! My name is {0}. How {1} can you be?"
undefined
> text.replace(/\{\d+\}/g, "")
'Hello world! My name is . How can you be?'
Through string.split. You just need to remove the anchors. ^ asserts that we are at the start and $ asserts that we are at the end. Because there isn't only a string {num} exists in a single line, your regex fails. And also remove the quotes which are around the regex delimiter /
> text.split(/\{\d+\}/).join("");
'Hello world! My name is . How can you be?'
You were close. What you want is: text = text.split(/\{\d+\}/).join("");
The two things that you missed were:
^ = the start of the string and $ = the end of the string. Since there are other characters around the pattern that you are trying to match, you don't want those.
if you are using a regular expression in the split() method, you need to use a RegExp object, not a string. Removing the "'s and just having the expression start and end with / will define a RegExp object.
I would actually agree with the others that the replace() method would be a better way to do what you are trying to accomplish, but if you want to use split() and join(), as you've stated, this is the change that you need.
You can just use replace mehthod:
var repl = text.replace(/\{\d+\} */g, '');
//=> "Hello world! My name is . How can you be?"

Replace all in javascript for one occurance

I have to replace "" (two quotes) with " (one quotes). I used:
string.replace(/""/g,'"')
but if it is having """" (four quotes) it is replacing with " (one quote) it is again replacing the "" (two quotes) with " (one quote).
I need """" (four quotes) should be replaced with "" (two quotes)
The code you provided in your question already does exactly what you say you want it to do:
'I like """"orange"""" and ""apple""'.replace(/""/g,'"');
// Returns:
'I like ""orange"" and "apple"'
'""'.replace(/""/g,'"');
// Returns:
'"'
'""""'.replace(/""/g,'"');
// Returns:
'""'
Unless you're missing some information in your question, there is nothing to solve.
for this reason, I believe the problem is somewhere else in your code.
If you want to replace four quotes with two quotes, this does it:
var string = "\"\"\"\"";
string = string.replace("\"\"\"\"", "\"\"")

Why this JavaScript RegExp results in dual answer?

Look at this simple HTML input tag:
<input type='text' id='phoneNumber' name='phoneNumber' class='inputBig textLeft'
data-validation='required regex'
data-validation-regex-pattern='^\\+\\d{2}\\.\\d{10}$'
value='+98.2188665544' />
<p id='log'></p>
Now imagine that we want to validate this field, using this function:
var log = $('#log');
function validateRegex(field) {
var pattern = field.attr('data-validation-regex-pattern');
log.append(pattern + '<br />');
if (pattern && pattern != '') {
var isValid = new RegExp(pattern).test(field.val().trim());
if (!isValid) {
log.append('not valid<br />');
}
else {
log.text('valid<br />');
}
}
}
validateRegex($('#phoneNumber'));
var isValid = new RegExp('^\\+\\d{2}\\.\\d{10}$').test($('#phoneNumber').val());
log.append(isValid.toString());
Now, if you look at the log, you see that this line returns false:
var isValid = new RegExp(pattern).test(field.val().trim());
However, this line of code returns true:
new RegExp('^\\+\\d{2}\\.\\d{10}$').test($('#phoneNumber').val().trim());
In other words, when the pattern of the RegExp object is passed to it as a string variable, it doesn't work. But when you pass a string literal, it works.
Why? What's wrong here?
To see it in action, look at this fiddle.
Escaping backslashes applies only to JavaScript, it isn't necessary for HTML. Therefore, the following attribute string:
data-validation-regex-pattern='^\+\d{2}\.\d{10}$'
Will work just fine:
Updated fiddle: http://jsfiddle.net/AndyE/GRL2m/6/
\\ is the method to write \ in a JavaScript String. The HTML data-attribute, written in JS would be \\\\, instead of \\.
Eg: <a data-x="\\">(HTML) is equivalent to '<a data-x="\\\\">' (JS).
To get your code work, replace double slashes (\\) in your HTML by a single slash.Fiddle: http://jsfiddle.net/GRL2m/5/
Extra information:
In HTML, HTML entities (eg ") are used to display special characters.
In JavaScript, escapes (eg \n, \x20, \u0009, ..) are used to display special characters.
In a RegExp, special RE characters have to be escaped by a slash (/\./). When the RegExp is constructed using a string, the slash has to be escaped, so that the slash also appear at the RegExp. "\." equals '.', while "\\." equals '\.'.

Categories

Resources