Alright, so I have a link using my custom syntax. This is part of my parser (sans the XSS scrubber part), and it's the problematic one that I've isolated one of the remaining bugs in. For some reason, the URI http://ur.i is getting truncated to merely "i".
Anyone who knows why gets a pony.
var str = "[inner -> http://ur.i]";
str = str.replace(/\[([^\]]+?)\s*(\||->)\s*((?!->)[^\]])+]/g, function(m, iH, separator, hr){
console.log('hr: '); console.log(hr);
return '<a class="'+ (separator.match(/->/) ? 'adlns-btn' : 'adlns-link') +'" href="'+ hr +'">' +
iH +
'</a>';
});
console.log(str);
The + quantifier should be inside the parentheses, not outside:
/\[([^\]]+?)\s*(\||->)\s*((?!->)[^\]]+)]/g
This solves the problem.
You lack to match the whitespace after -> , try the following:
/\[([^\]]+?)\s*(\||->)\s*((?!->\s)[^\]])+]/g
Related
So basically what I'm trying to do is print a simple string to the screen using the console.log function.
Here's an example :
const fromLabel: string = '["' + "AppExp" + '"]' + '\n' + '["' + "AppExp" + '"]';
And I ultimately wanna print it, so I go:
console.log(fromLabel);
and my output is:
[\"AppExp\"]\n[\"AppExp\"]
So, basically no carriage return and unwanted '\'.
Any idea what could be the problem?
EDIT: Never mind. I was working with objects and to print them I used JSON.stringify.. little did I know I used it on this string as well ..my bad
Backslashes are escaping certain characters in the string. Your string is put together in a weird way—you're mixing "" and ''. Try this:
var str = '["' + 'AppExp' + '"]' + '\n' + '["' + 'AppExp' + '"]'
console.log(str)
try this code with template literals
I omitted the : string to be able to run the snippet but remember to add it!
const fromLabel = `[""AppExp""]
[""AppExp""]`;
console.log(fromLabel);
or in case you do not want duplicate " chars
const fromLabel: string = `["AppExp"]
["AppExp"]`;
I hope it helps! :)
I'm struggling to get a string replaced in Javascript by a regex matching pattern.
I want to replace all matches of {{$myparam}} to be surrounded by a span tag.
This works (see code below). But I want to prevent replacements when a match is preceded by href=".
Example: href="{{$myparam}} must NOT be replaced.
{{$myparam}} MUST be replaced.
myparam can be any text string.
var highlighted = html.replace(/(\{\{(.*?)\}\})/g, function highlight(x) {
return "<span class='highlight'>" + x + "</span>";
});
I've checked out numerous examples in other threads, but I cannot find a solution that works for my case.
You could use
var subject = 'href="{{$myparam}}" or any other {{$myparam}}';
var regex = /"[^"]*"|(\{\{(.*?)\}\})/g;
replaced = subject.replace(regex, function(m, group1) {
if (typeof group1 == 'undefined') return m;
else return "<span class='highlight'>" + group1 + "</span>";
});
alert(replaced);
# href="{{$myparam}}" or any other <span class='highlight'>{{$myparam}}</span>
See a demo on regex101.com.
The idea here is to check for
not_interesting|not_interesting_either|(very_interesting)
and check for the presence of a captured group. You can put anything not interesting to the left as in this example: "[^"]*" (that is anything between double quotes).
If you want to read more on the subject, have a look here.
This seems a bit simpler, just make the href part optional:
mystring = 'this has {{$param1}} and {{$param2}} and href="{{$param3}}" too';
console.log(mystring
.replace(/(href=.)?\{\{([^{} ]+)\}\}/g,
function (match,chk,param) {
return "undefined" !== typeof(chk)
? match
: '<span class="highlight">' + param + '</span>';
}));
The second argument to the callback function is the 'check' part, and the third argument is the captured parameter name. Since the check part is optional and it's fairly precise, it'll only be defined at all if it's 'href="'.
Output, with newlines added for readability:
this has <span class="highlight">$param1</span>
and <span class="highlight">$param2</span>
and href="{{$param3}}" too
I swear i tried figuring this out myself all day, but my regex-foo is just not that good.
I'm trying to create a small parser function to convert strings with urls to html coded and tags
I know how complex a regex can be trying to figure out which urls to covert to what from a big string, so what I did is simply prefix the string to covert with a flag to tell the parser how to format it, and post fix it with the ";" char to tell the parser where that particular URL ends. This way the parser has lesser guest work to do resulting in easier to regex-match and faster for execution. I really dont need a generalize match and replace all.
So my formatting is as follows, where "X" is the url string:
For URLs it will be url=X;
For IMAGES it will be img=X;
so anything in between my prefix and post fix must be converted accordingly..
So for example, for images in my document, the string could be:
click this image img=http://example.com/image1.jpg;
and i need that converted to
click this image <a href="http://example.com/image1.jpg" target="_blank">
<img class="img img-responsive" src="http://example.com/image1.jpg"/></a>
I am able to do this easily in PHP buy preg_match() function
preg_match('/\img=(.+?)\;/i', $item_des, $matches)
here's the code block:
I decided to push this routine to the browser instead of the backend (PHP) so i need similar or better JS solution.
Hoping anyone can help here, thanks!
try code below:
var str = "click this image img=http://example.com/image1.jpg;image2 img=http://example.com/image2.jpg;"
var phrases = str.split(';');
var totalRes = '';
phrases.forEach(function(str){
totalRes += processPhrase(str);
});
console.log(totalRes);
function processPhrase(str) {
var img = str.split('img=')
var res = '';
if (img.length > 1) { //img=X
var url = img[1].replace(';', '');
res = img[0] + "<a href='" + url + "' target='_blank'><img src='" + url + "'/></a>";
} else {
var url = str.split('url=');
//Do for url=X here
}
console.info(res);
return res;
}
You can use this regexp /(img|url)=(.+?);/g:
(img|url) : the type, should be grouped so we will know what to do with the value
= : literal "="
(.+?) : a number of characters (use the non-greedy ? so it will match as fewer as possible)
; : literal ";"
Read more about non-greedy regexps here.
Example:
var str = "click this image img=http://i.imgur.com/3wY30O4.jpg?a=123&b=456; and check this URL url=http://google.com/;. Bye!";
// executer is an object that has functions that apply the changes for each type (you can modify the functions for your need)
var executer = {
"url": function(e) {
return '<a target="_blank" href="' + e + '">' + e + '</a>';
},
"img": function(e) {
return '<a target="_blank" href="' + e + '"><img src="' + e + '"/></a>';
}
}
var res = str.replace(/(img|url)=(.+?);/g, function(m, type, value) {
return executer[type](value); // executer[type] will be either executer.url or executer.img, then we pass the value to that function and return its returned value
});
console.log(res);
var str = 'let us pretend that this is a blog about gardening&cooking; here's an apostrophe & ampersand just for fun.';
This is the string I'm operating on. The desired end result is: "let us pretend that this is a blog about gardening&cooking; here's an apostrophe & ampersand just for fun."
console.log('Before: ' + str);
str = str.replace(/&(?:#x?)?[0-9a-z]+;?/gi, function(m){
var d = document.createElement('div');
console.log(m);
d.innerHTML = m.replace(/&/, '&');
console.log(d.innerHTML + '|' + d.textContent);
return !!d.textContent.match(m.replace(/&/, '&')[0]) ? m : d.textContent;
});
console.log('After: ' + str);
The problem is that HTML doesn't support XML's '
To avoid the issue you should use ' instead of '
For more information look at this post:
Why shouldn't ' be used to escape single quotes?
This should do what you want:
str.replace(/&([#x]\d+;|[a-z]+;)/g, "&$1")
or, with a positive lookahead:
str.replace(/&(?=[#x]\d+;|[a-z]+;)/g, "&")
I don't think you need any HTML2text en-/decoding.
var html = "<div>"+title+"<br/>";
document.write(title.replace(/ /g,"-"));
html+= '<p><a href="go.aspx?title=' + title + '">Details<\/a></p></div>';
I want to replace title space with dash.
Try title.replace(/\s/g , "-") instead. (/\s/ is the regex escape for whitespace).
Also, do:
title = title.replace(/\s/g , "-");
var html = "<div>" + title + "</div>";
// ...
I find regex expressions commonly used in the replace function very hard to read - plus it's easy to forget to not quote the string you are searching for or to omit the /g to indicate a global replace. For doing something simple like replacing a space with a dash, using an easier to understand "split" followed by a "join" is just as fast.
alert("this is a test".split(" ").join("-"));
https://jsfiddle.net/n0u3aw5c/
Calling title.replace will not change title, but return a string where the values have been replaced. You need to use the returned value:
var html = "<div>"+title+"<br/>";
var newTitle = document.write(title.replace(/ /g,"-"));
html+= '<p><a href="go.aspx?title=' + newTitle + '">Details<\/a></p></div>';
The regular expression is fine, but will only replace spaces and not all whitespace.
var str = "Tatwerat Development Team";
str = str.replace(/\s+/g, '-');
document.write(str)
ehdv's answer gets you 90% of the way there. I just wanted to clarify where the code he suggested would go within your code, and it wouldn't look right in a comment.
var html = "<div>" + title + "<br/>";
title = title.replace(/\s/g , "-");
html+= '<p><a href="go.aspx?title=' + title + '">Details<\/a></p></div>';
This assumes that you DON'T want dashes in the div, but you DO in the URL.
And if you also want to replace multiple spaces that come immediately one after another with a SINGLE dash instead of ending up with double dashes in your title, use this instead:
var html = "<div>" + title + "<br/>";
title = title.replace(/\s+/g , "-");
html+= '<p><a href="go.aspx?title=' + title + '">Details<\/a></p>
I'd also like to mention that you're not closing your div. Maybe you just didn't include that part of your code but it's worth mentioning. There's also an unnecessary \ in your string. It's not hurting anything, but it's not needed. Maybe your code is meant to look like this:
var html = "<div>" + title + "</div>";
title = title.replace(/\s/g , "-");
html+= '<p>Details</p>