is it possible to create a value with these characteristics with key addBlueborder?
var Object = {
footer: '#footer',
mockup: '#mockup',
// My dude??????
addBlueborder: '"input[name='"+ oBlock +"_fix']"'
};
I don't know to escape with double quote.
I would like to make that:
$(Object.addBlueborder).each(function(e) { ... };
thanks
You have quotes confusion. It should be like this
addBlueborder: 'input[name="' + oBlock + '_fix"]'
Also note, that quotes around the attribute are not really necessary if your oBlock doesn't contain spaces or other weird characters. In this case expression will become even simpler
addBlueborder: 'input[name=' + oBlock + '_fix]'
Related
I have an object,
var obj = {};
Where I set a property
obj['prop'] = 'This is a "property"'
How can I stop
JSON.stringify(obj)
from returning
"This is a \"property\""
and instead return
"This is a "property""
Ideally, is there a way to do this where I set the property? i.e.
obj['prop'] = 'This is a "property"'
If you really want this, you might use something like JSON.stringify(obj).replace(/\\/g,'').
Beware: the output will NOT be a valid JSON, and dataloss can occur if you have any 'legit' backslashes in your JSON.
As explained in the comment, you cannot prevent that a double quote (") is being escaped because that character is reserved (defined in specs). What you can do is do use a work-around: use a single quote ' to quote something in a text.
If you still want to see a double quote here-after, then it's something difficult to achieve. Replacing the ' into " is not enough because there are words that use ' naturally. Like it's or don't
const obj = {};
obj['myKey'] = "first word is 'Hello World'";
obj['anotherKey'] = "second word is 'Lorum Ispum'...";
console.log(JSON.stringify(obj));
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 have variable var str as following:
var str = <option value="1">tea</option>;
I would like to make it as below
var quote_str = '<option value="1">tea</option>;'
Is there anyone can help me? Thanks in advance!
Edit:
I have tried the following code,however, it's not correct.
var quote_str = 'str';
I think that you want the semicolon outside the string literal:
var quote_str = '<option value="1">tea</option>';
If you mean that you want apostrophe characters inside the string also, you can use \' to put an apostrophe in a string delimited by apostrophes:
var quote_str = '\'<option value="1">tea</option>\'';
You can also use quotation marks to delimit the string. Then you don't have to escape the apostrophes, but you have to escape the quotation marks:
var quote_str = "'<option value=\"1\">tea</option>'";
If you already have a string, and want to add apostrophes around it, you concatenate strings:
var quote_str = "'" + str + "'";
Escape each single quote with a back-slash:
var quote_str = '\'<option value="1">tea</option>;\''
…or wrap the string in quotes of a different kind (i.e. double quotes), but be sure to escape the inner double quotes as to not unintentionally close the string:
var quote_str = "'<option value=\"1\">tea</option>;'"
late update: now we have template literals, so the whole thing becomes a breeze:
var quote_str = `'<option value="1">tea</option>;'`
You can escape characters in Javascript with the \. If that's your issue
We can use the backslash () escape character to prevent JavaScript from interpreting a quote as the end of the string.
The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.
Using this method, we can use apostrophes in strings built with ".
'We\'re safely using an apostrophe in single quotes.' We can also use quotation marks in strings built with ".
"Then he said, \"Hello, World!\"";
In my case, i'm unable to use the notation of ${} in rendered Javascript inside Python Mako Templates as it's already using ${} for rendering variables in Mako:
# mako template somewhere
var quote_str = `'${str}'`;
So i just wrote a small function:
# app.js ( a real Javascript file )
function singlequote(text) {
return `'${text}'`;
}
And then I use:
# mako template somewhere
var quote_str = singlequote(str);
# So i'm able to also use something like:
let btn = '<button type="button" onclick="update(' + singlequote(myid) + "," + singlequote(mystate) + ')"> Update </button>';
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.
I need a regular expression to strip out any BBCode in a string. I've got the following (and an array with tags):
new RegExp('\\[' + tags[index] + '](.*?)\\[/' + tags[index] + ']');
It picks up [tag]this[/tag] just fine, but fails when using [url=http://google.com]this[/url].
What do I need to change? Thanks a lot.
I came across this thread and found it helpful to get me on the right track, but here's an ultimate one I spent two hours building (it's my first RegEx!) for JavaScript and tested to work very well for crazy nests and even incorrectly nested strings, it just works!:
string = string.replace(/\[\/?(?:b|i|u|url|quote|code|img|color|size)*?.*?\]/img, '');
If string = "[b][color=blue][url=www.google.com]Google[/url][/color][/b]" then the new string will be "Google". Amazing.
Hope someone finds that useful, this was a top match for 'JavaScript RegEx strip BBCode' in Google ;)
You have to allow any character other than ']' after a tag until you find ' ]'.
new RegExp('\\[' + tags[index] + '[^]]*](.*?)\\[/' + tags[index] + ']');
You could simplify this to the following expression.
\[[^]]*]([^[]*)\[\\[^]]*]
The problem with that is, that it will match [WrongTag]stuff[\WrongTag], too. Matching nested tags requires using the expression multiple times.
You can check for balanced tags using a backreference:
new RegExp('\\[(' + tags.Join('|') + ')[^]]*](.*?)\\[/\\1]');
The real problem is that you cant't match arbitrary nested tags in a regular expression (that's the limit of a regular language). Some languages do allow for recursive regular expressions, but those are extensions (that technically make them non-regular, but doesn't change the name that most people use for the objects).
If you don't care about balanced tags, you can just strip out any tag you find:
new RegExp('\\[/?(?:' + tags.Join('|') + ')[^]]*]');
To strip out any BBCode, use something like:
string alltags = tags.Join("|");
RegExp stripbb = new RegExp('\\[/?(' + alltags + ')[^]]*\\]');
Replace globally with the empty string. No extra loop necessary.
I had a similar problem - in PHP not Javascript - I had to strip out BBCode [quote] tags and also the quotes within the tags. Added problem in that there is often arbitrary additional stuff inside the [quote] tag, e.g. [quote:7e3af94210="username"]
This worked for me:
$post = preg_replace('/[\r\n]+/', "\n", $post);
$post = preg_replace('/\[\s*quote.*\][^[]*\[\s*\/quote.*\]/im', '', $post);
$post = trim($post);
lines 1 and 3 are just to tidy up any extra newlines, and any that are left over as a result of the regex.
I think
new RegExp('\\[' + tags[index] + '(=[^\\]]+)?](.*?)\\[/' + tags[index] + ']');
should do it. Instead of group 1 you have to pick group 2 then.
Remember that many (most?) regex flavours by default do not let the DOT meta character match line terminators. Causing a tag like
"[foo]dsdfs
fdsfsd[/foo]"
to fail. Either enable DOTALL by adding "(?s)" to your regex, or replace the DOT meta char in your regex by the character class [\S\s].
this worked for me, for every tag name. it also supports strings like '[url="blablabla"][/url]'
str = str.replace(/\[([a-z]+)(\=[\w\d\.\,\\\/\"\'\#\,\-]*)*( *[a-z0-9]+\=.+)*\](.*?)\[\/\1\]/gi, "$4")