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

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

Related

JS conditional RegEx that removes different parts of a string between two delimiters

I have a string of text with HTML line breaks. Some of the <br> immediately follow a number between two delimiters «...» and some do not.
Here's the string:
var str = ("«1»<br>«2»some text<br>«3»<br>«4»more text<br>«5»<br>«6»even more text<br>");
I’m looking for a conditional regex that’ll remove the number and delimiters (ex. «1») as well as the line break itself without removing all of the line breaks in the string.
So for instance, at the beginning of my example string, when the script encounters »<br> it’ll remove everything between and including the first « to the left, to »<br> (ex. «1»<br>). However it would not remove «2»some text<br>.
I’ve had some help removing the entire number/delimiters (ex. «1») using the following:
var regex = new RegExp(UsedKeys.join('|'), 'g');
var nextStr = str.replace(/«[^»]*»/g, " ");
I sure hope that makes sense.
Just to be super clear, when the string is rendered in a browser, I’d like to go from this…
«1»
«2»some text
«3»
«4»more text
«5»
«6»even more text
To this…
«2»some text
«4»more text
«6»even more text
Many thanks!
Maybe I'm missing a subtlety here, if so I apologize. But it seems that you can just replace with the regex: /«\d+»<br>/g. This will replace all occurrences of a number between « & » followed by <br>
var str = "«1»<br>«2»some text<br>«3»<br>«4»more text<br>«5»<br>«6»even more text<br>"
var newStr = str.replace(/«\d+»<br>/g, '')
console.log(newStr)
To match letters and digits you can use \w instead of \d
var str = "«a»<br>«b»some text<br>«hel»<br>«4»more text<br>«5»<br>«6»even more text<br>"
var newStr = str.replace(/«\w+?»<br>/g, '')
console.log(newStr)
This snippet assumes that the input within the brackets will always be a number but I think it solves the problem you're trying to solve.
const str = "«1»<br>«2»some text<br>«3»<br>«4»more text<br>«5»<br>«6»even more text<br>";
console.log(str.replace(/(«(\d+)»<br>)/g, ""));
/(«(\d+)»<br>)/g
«(\d+)» Will match any brackets containing 1 or more digits in a row
If you would prefer to match alphanumeric you could use «(\w+)» or for any characters including symbols you could use «([^»]+)»
<br> Will match a line break
//g Matches globally so that it can find every instance of the substring
Basically we are only removing the bracketed numbers if they are immediately followed by a line break.

input value formation with double quotation marks and single quotes [duplicate]

This question already has answers here:
Escaping single quotes in JavaScript string for JavaScript evaluation
(9 answers)
Closed 4 years ago.
I have problem in the input "value".
$("#printCard").append("<input type='hidden' name='textCard' value='that aren't on the battlefield have flash. ' id='texting'>");
or JSON:
$("#demo").append("<input type='hidden' name='textCard' value='"+ infoCard.text +"' id='texting'>" );
Result:
<input name="textCard" value="that aren" t="" on="" the="" battlefield="" have="" flash.="" '="" id="texting" type="hidden">
The problem is double quotation marks and single quotes(aren't..).
This example:
The two options I have to save, double quotation marks and single quotes.
thank you all
If you don't need to support IE use template literals. TL are strings that have an easier syntax and extra properties. Here's a comparison between TL and SL (String Literal):
Syntax
SL: Wrap strings in double or single quotes. If the content of string has quotes as well, they should either be escaped by being prefixed with a backslash:
\" and \'
OR use HTML entities:
‘ or ‘ (Left Single QUOtation mark)
’ or ’ (Right Single QUOtation mark)🟊
“ or “ (Left Double QUOtation mark)
” or ” (Right Double QUOtation mark)
Note: These particular quotes represented by HTML entities are the curvy or smart quotes type and can only be used in plain text not code. The quotes used in code are straight, do not confuse them as universally accepted they are as different as a comma is to a period.
🟊 It's ok to use ’ as an apostrophe - Unicode9.0.0, ch06, pg. 276
TL: Wrap strings in backticks, also called grave accent, On a QWERTY keyboard the key is located at the top left corner `.
`template literal`
Concatenation vs. Interpolation
SL: A mess of single quotes, double quotes, and pluses:
var str = '<input id="'+ID+'" class="form-control">';
TL: Wrap variables and expressions in: ${...}:
var str = `<input id="${ID}" class="form-control">`;
Demo
var infoCard = {
text: "that aren’t on the battlefield have flash."
};
$("#printCard0").append(`<input type='hidden' name='textCard' value='that aren’t on the battlefield have flash.' id='texting0'>`);
$("#printCard1").append(`<input type='hidden' name='textCard' value='${infoCard.text}' id='texting1'>`);
<main id='core'>
<figure id='printCard0'></figure>
<figure id='printCard1'></figure>
</main>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I recommend using the object-based method, then you don't have to worry about special characters in HTML.
$("#printCard").append($("<input>", {
type: "hidden",
name: "textCard",
value: infoCard.text,
id: "texting"
});

why isn't this javascript regex split function working?

I'm trying to split a string by either three or more pound signs or three or more spaces.
I'm using a function that looks like this:
var produktDaten = dataMatch[0].replace(/\x03/g, '').trim().split('/[#\s]/{3,}');
console.log(produktDaten + ' is the data');
I need to clean the data up a bit, hence the replace and trim.
The output I'm getting looks like this:
##########################################################################MA-KF6###Beckhoff###EL1808 BECK.EL1808###MA-KF7###Beckhoff###EL1808 BECK.EL1808###MA-KF12###Beckhoff###EL1808 BECK.EL1808###MA-KF13###Beckhoff###EL1808 BECK.EL1808###MA-KF14###Beckhoff###EL1808 BECK.EL1808###MA-KF15###Beckhoff###EL1808 BECK.EL1808###MA-KF16###Beckhoff###EL1808 BECK.EL1808###MA-KF19###Beckhoff###EL1808 BECK.EL1808 is the data
How is this possible? Irrespective of the input, shouldn't the pound and multiple spaces be deleted by the split?
You passed a string to the split, the input string does not contain that string. I think you wanted to use
/[#\s]{3,}/
like here:
var produktDaten = "##########################################################################MA-KF6###Beckhoff###EL1808 BECK.EL1808###MA-KF7###Beckhoff###EL1808 BECK.EL1808###MA-KF12###Beckhoff###EL1808 BECK.EL1808###MA-KF13###Beckhoff###EL1808 BECK.EL1808###MA-KF14###Beckhoff###EL1808 BECK.EL1808###MA-KF15###Beckhoff###EL1808 BECK.EL1808###MA-KF16###Beckhoff###EL1808 BECK.EL1808###MA-KF19###Beckhoff###EL1808 BECK.EL1808";
console.log(produktDaten.replace(/\x03/g, '').trim().split(/[#\s]{3,}/));
This /[#\s]{3,}/ regex matches 3 or more chars that are either # or whitespace.
NOTE: just removing ' around it won't fix the issue since you are using an unescaped / and quantify it. You actually need to quantify the character class, [#\s].

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

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 + '"'

Javascript:Replace single characters after the string

I'm trying to do something which seems fairly basic, but can't seem to get it working.
I'm trying to strip the characters after the last instance of an underscore.
I have this long Query String:
json_data=demo_title=Demo+title&proc1_script=script.sh+parameters&proc1_chk_make=on&outputp2_value=&demo_input_description=hola+mundo&outputp4_visible=on&outputp4_info=&inputdata1_max_pixels=1024000&tag=&outputp1_id=nanana&proc1_src_compresion=zip&proc1_chk_cmake=off&outputp3_description=&outputp3_value=&inputdata1_description=input+data+description&inputp2_description=bien%3F&inputp3_description=funciona&proc1_cmake=-D+CMAKE_BUILD_TYPE%3Astring%3DRelease+&outputp2_visible=on&outputp3_visible=on&outputp1_type=header&inputp1_type=text&demo_params_description=va+bien&outputp1_description=&inputdata1_type=image2d&proc1_chk_script=off&demo_result_description=win%3F&outputp2_id=nanfdsvfa&inputp1_description=funciona&demo_wait_description=boh&outputp4_description=&inputp2_type=integer&inputp2_id=papapa&outputp1_value=&outputp3_id=nananartrtrt&inputp3_id=pepepe&outputp3_type=header&inputp3_visible=+off&outputp1_visible=on&inputdata1_id=id_lsd&outputp4_value=&inputp2_visible=on&proc1_source=lsd-1.5.zip&inputp3_value=si&proc1_make=-j4+-C+&images_config_file=cfgmydemo.cfg&outputp2_type=header&proc1_subdir=xxx-1.5&proc1_url=http%3A%2F%2Fwww.ipol.im%2Fpub%2Falgo%2F...&inputdata1_image_depth=1x8i&inputp1_id=popopo&inputp1_value=si&inputp2_value=no&demo_data_filename=data_saved.cfg&inputdata1_info=info_lsd&outputp3_info=&inputdata1_image_format=.pgm&outputp1_info=&inputdata1_compress=False&inputp1_visible=on&proc1_id=lsd&outputp4_id=nana&outputp2_description=&outputp4_type=header&outputp2_info=&inputp3_type=float&&tag&inputp4_iddcksmdclk&inputp4_typetext&inputp4_descriptionkldmsclk&inputp4_valueklcdmkl&inputp4_infoclkdmscdl
Now I replace the separator = in separator %24+ and & in +%23+ using fr=fr.replace(/\&/g,"+%23+");
Separator
javascript Mako
= %24+
& +%23+
But the result is:
json_data%24+demo_title%24+Demo+title+%23+proc1_script%24+script.sh+parameters+%23+proc1_chk_make%24+on+%23+outputp2_value%24++%23+demo_input_description%24+hola+mundo+%23+outputp4_visible%24+on+%23+outputp4_info%24++%23+inputdata1_max_pixels%24+1024000+%23+tag%24++%23+outputp1_id%24+nanana+%23+proc1_src_compresion%24+zip+%23+proc1_chk_cmake%24+off+%23+outputp3_description%24++%23+outputp3_value%24++%23+inputdata1_description%24+input+data+description+%23+inputp2_description%24+bien%3F+%23+inputp3_description%24+funciona+%23+proc1_cmake%24+-D+CMAKE_BUILD_TYPE%3Astring%3DRelease++%23+outputp2_visible%24+on+%23+outputp3_visible%24+on+%23+outputp1_type%24+header+%23+inputp1_type%24+text+%23+demo_params_description%24+va+bien+%23+outputp1_description%24++%23+inputdata1_type%24+image2d+%23+proc1_chk_script%24+off+%23+demo_result_description%24+win%3F+%23+outputp2_id%24+nanfdsvfa+%23+inputp1_description%24+funciona+%23+demo_wait_description%24+boh+%23+outputp4_description%24++%23+inputp2_type%24+integer+%23+inputp2_id%24+papapa+%23+outputp1_value%24++%23+outputp3_id%24+nananartrtrt+%23+inputp3_id%24+pepepe+%23+outputp3_type%24+header+%23+inputp3_visible%24++off+%23+outputp1_visible%24+on+%23+inputdata1_id%24+id_lsd+%23+outputp4_value%24++%23+inputp2_visible%24+on+%23+proc1_source%24+lsd-1.5.zip+%23+inputp3_value%24+si+%23+proc1_make%24+-j4+-C++%23+images_config_file%24+cfgmydemo.cfg+%23+outputp2_type%24+header+%23+proc1_subdir%24+xxx-1.5+%23+proc1_url%24+http%3A%2F%2Fwww.ipol.im%2Fpub%2Falgo%2F...+%23+inputdata1_image_depth%24+1x8i+%23+inputp1_id%24+popopo+%23+inputp1_value%24+si+%23+inputp2_value%24+no+%23+demo_data_filename%24+data_saved.cfg+%23+inputdata1_info%24+info_lsd+%23+outputp3_info%24++%23+inputdata1_image_format%24+.pgm+%23+outputp1_info%24++%23+inputdata1_compress%24+False+%23+inputp1_visible%24+on+%23+proc1_id%24+lsd+%23+outputp4_id%24+nana+%23+outputp2_description%24++%23+outputp4_type%24+header+%23+outputp2_info%24++%23+inputp3_type%24+float+%23++%23+tag+%23+inputp4_iddcksmdclk+%23+inputp4_typetext+%23+inputp4_descriptionkldmsclk+%23+inputp4_valueklcdmkl+%23+inputp4_infoclkdmscdl
Now I am interested how to replace this = after the value jsondata.
Explain:
In the Query string there is the string json_data+%23+ and this +%23+ I want replace to =
How?
Strip the characters after the last instance of an underscore:
json_data.substring(0, json_data.lastIndexOf("_"));
Replace +%23+ with =
json_data.replace("+%23+", "=");
However, if you're trying to turn all the %xx into what they're supposed to be, you should url decode the string instead.
Which would probably have to be something like:
decodeURIComponent((json_data).replace('+', '%20'));

Categories

Resources