Why does this line work
$('#body-image').css("background-image", 'url('+ backgroundimage +')');
but not this one
$('#body-image').css("background-image", 'url('backgroundimage')');
or this one
$('#body-image').css("background-image", 'url(backgroundimage)');
backgroundimage is a JavaScript variable. The concatenation operator in JavaScript is +, so to put a string together with a variable, you do 'some string ' + someVariable. Without the +'s, JavaScript wouldn't know what to do with your variable (and in your third example, wouldn't even know that it was a variable).
You need to concat the string with the variable backgroundimage. So you use "+" for this.
That's why this doesn't work.
$('#body-image').css("background-image", 'url('backgroundimage')');
And the secont doesn't work because there is no image called 'backgroundimage'.
$('#body-image').css("background-image", 'url(backgroundimage)');
Because you are building a string. You are missing the line where backgroundimage gets a value:
var backgroundimage = "someimage.gif";
$('#body-image').css("background-image", 'url('+ backgroundimage +')');
becomes:
$('#body-image').css("background-image", 'url(someimage.gif)');
it's concatenating the string.
let's say backgroundimage is 'foo.jpg, then
'url('+backgroundimage+')' = 'url(foo.jpg)'
In JavaScript, a string literal (i.e., "I am a string") is actually treated like a String object (though, strictly speaking, it isn't - see the MDC documentation - but we can ignore the difference at this level). The following two lines are equivalent:
var letters = "ABC", numbers = "123";
var letters = new String("ABC"), numbers = new String("123");
Strings are concatenated using either the + operator or the String.concat method, either of which join 2 or more strings in a left-to-right order and return the result. So in order to get "ABC123", we can do any of the following:
"ABC" + "123"
"ABC" + numbers
letters + "123"
letters + numbers
"ABC".concat("123")
"ABC".concat(numbers)
letters.concat("123")
letters.concat(numbers)
but not:
letters"123"
"ABC"numbers
lettersnumbers
"lettersnumbers"
which are all, effectively, the same thing that you were trying to do in your examples.
Related
Why, when I change this function variable "endc" to normal text example
let endc = "here is path as string"
then is working - when I want to get "path" from function then my code is broken
there is my problem - why?
The + operator is overloaded for String class, so both the operand must be String for it to work.
Here your variable endc is type of URL. So the + doesn't work for String and URL.
Better to convert your URL into string and then use +, like this:
var welcome = js + endc.absoluteString + typer
Now, it should work.
Also, I think you should add your semicolon in the typer string itself.
I'd like to know if I can parse & filter JSON text data based on a regular expression; say for example I have the following
{"key":"some:xx:yy", "value": 72311}
{"key":"some:xx:zz", "value": 72311}
{"key":"some:xx:qq", "value": 72311}
I want to select all tuples that have for the key field the same "some:xx:" part, how can I archive this using JSON in an 'elegant' way?
The example you gave contains three different objects. So you can use javascript to look for text in a property.
obj1 = {"key":"some:xx:yy", "value": 72311};
if (obj1.key.indexOf("xx") !== -1) { // obj1.key contains "xx"
//do something
}
If you have an array with those values, then you can simply loop through the array and look for "xx" just like above for each element of array. And when found, you can assign that element to another array. So at the end of the loop, "another array" will contain all elements that contain "xx".
If you don't insist on using RegEx, i can show you an example code for the loop. If you insist on RegEx, let me know and i will help you.. just kidding, let me know and i will delete my answer and silently leave this question :)
I'm going to give you a straight answer to the question you asked, but hopefully the complexity and the raft of caveats will convince you that JSON.parse is a better alternative.
You can write a regular expression to match a single such tuple, but you can't write a regular expression to match all such tuples.
To explain why, consider the regular expression that matches one:
var stringBody = '(?:[^"\\\\]|\\\\.)*';
var string = '"' + stringBody + '"';
var space = '[ \t\r\n\f]*';
var colon = space + ':' + space;
var comma = space + ',' + space;
var uglyRegex = '^(?:[^"]|' + string + ')*?'
+ '"key"' + colon + '"(some:xx:' + stringBody + ')"' + comma
+ '"value"' + colon + '((?:[^\},"]|' + string + ')*)';
This works by finding the minimal number of non-string or full-string tokens that precede a key whose value starts with some:xx: and then looks for a value.
It leaves the key in matching group 1 and the value in matching group 2.
Since it has to match starting at the beginning to correctly identify string token boundaries, it cannot be used in a 'g' flag match.
Caveats
It assumes certain characters in "key"'s property value are not \uABCD escaped.
It assumes characters in the property names "key" and "value" are not \uABCD escaped.
It requires the key and value to occur in that order.
It cannot tell what other properties occur in the same object.
Each of these problems could be worked around by making the regex much more complex, but with regular expressions, often, the only way to handle a corner case is to make the regex much bigger.
When incremental improvements to code explode the size, the code is unmaintainable.
I'm having difficulties with constructing some regular expressions using Javascript.
What I need:
I have a string like: Woman|{Man|Boy} or {Girl|Woman}|Man or Woman|Man etc.
I need to split this string by '|' separator, but I don't want it to be split inside curly brackets.
Examples of strings and desired results:
// Expample 1
string: 'Woman|{Man|Boy}'
result: [0] = 'Woman', [1] = '{Man|Boy}'
// Example 2
string '{Woman|Girl}|{Man|Boy}'
result: [0] = '{Woman|Girl}', [1] = '{Man|Boy}'
I can't change "|" symbol to another inside the brackets because the given strings are the result of a recursive function. For example, the original string could be
'Nature|Computers|{{Girls|Women}|{Boys|Men}}'
try this:
var reg=/\|(?![^{}]+})/g;
Example results:
var a = 'Woman|{Man|Boy}';
var b = '{Woman|Girl}|{Man|Boy}';
a.split(reg)
["Woman", "{Man|Boy}"]
b.split(reg)
["{Woman|Girl}", "{Man|Boy}"]
for your another question:
"Now I have another, but a bit similar problem. I need to parse all containers from the string. Syntax of the each container is {sometrash}. The problem is that container can contain another containers, but I need to parse only "the most relative" container. mystring.match(/\{+.+?\}+/gi); which I use doesn't work correctly. Could you correct this regex, please? "
you can use this regex:
var reg=/\{[^{}]+\}/g;
Example results:
var a = 'Nature|Computers|{{Girls|Women}|{Boys|Men}}';
a.match(reg)
["{Girls|Women}", "{Boys|Men}"]
You can use
.match(/[^|]+|\{[^}]*\}/g)
to match those. However, if you have a nesting of arbitrary depth then you'll need to use a parser, [javascript] regex won't be capable of doing that.
Test this:
([a-zA-Z0-9]*\|[a-zA-Z0-9]*)|{[a-zA-Z0-9]*\|[a-zA-Z0-9]*}
I am trying to replace multiple values in a string with JS replace(). The values that I want to replace include line breaks, &, #, etc... I know how to replace one value:
var string = document.getElementById('string').value.replace(\/n/g, '<br>');
However, what is the syntax to include other values. For example, how can I make the below replace functions one function?
var string = document.getElementById('string').value.replace(\/n/g, '<br>')
var string = document.getElementById('string').value.replace('&', '%26');
You could chain it simply.
var string = document.getElementById('string').value.replace(/\n/g, '<br>').replace('&', '%26');
I am trying to replace a certain text in Javascript.
newexp is a variable.
numexp is a variable
replacenamestring = new RegExp('Memberresumeexp\[1\]',"ig");
newexp = newexp.replace(replacenamestring,'Memberresumeexp[' + numexp + ']');
The above replace is not working.
How ever this works.
newexp = newexp.replace(/Memberresumeexp\[1\]/ig,'Memberresumeexp[' + numexp + ']');
Not able to figure out why?
Your first line creates a Javascript string, then parses the string as a regex.
Javascript string literals use \ as an escape character, so the \s are not part of the string value. Therefore, the [ and ] in your regex aren't escaped, so it's creating a character class.
You need to escape the \s by writing \\.
Here's a working example for you with one BIG caveat -- I changed "[1]" to "[\d+]" just in case you needed this for more cases of Memberresumeexp[<any number>]. Also, I hardcoded numexp, because I had not seen how it was initialized.
var replacenamestring = new RegExp('Memberresumeexp\\[\\d+\\]',"ig");
var newexp = "asdfasdflkj;lakwjef Memberresumeexp[1] asdfasdfasdf\nqwerqwerwer Memberresumeexp[2] qwerqwerwqerewr\n";
var numexp = 123;
if(replacenamestring.test(newexp))
{
newexp = newexp.replace(replacenamestring,'Memberresumeexp[' + numexp + ']');
}
It's a simple lexical syntax issue. In the first case, you're creating the RegExp object with the constructor, which starts from a string constant. Well, string constants have their own syntactic quirks, and in particular those backslashes in the string will be interpreted during its own parsing. By the time the RegExp constructor is called, those are gone.
The "native" RegExp syntax has its own quoting rules, which are such that the "[" and "]" portions of the pattern are correctly interpreted when you use that syntax.