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>
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 need your help,
How can the existing code below be modified such that it not only takes into account replacing all the <br>'s with \n's but also all the <nbsp;>'s anywhere in a string with the space separator in javascript?
Here is the existing code that needs to be modified:
var txt = str.replace(/<br\s*\/?>/mg,"\n")
If you want to do it with one regexp, replace accepts a function as the replacer so you could leverage that with a group match:
var str = 'some string <br/> and something else';
var txt = str.replace(/(<br\s*\/?>| )/mg, function (match) {
return match === ' ' ? ' ' : '\n';
});
document.write('<pre>' + txt + '</pre>');
If not, you can also chain together as many replace calls as you want:
var str = 'some string <br/> and something else';
var txt = str.replace(/<br\s*\/?>/gm, '\n').replace(/ /gm, ' ');
document.write('<pre>' + txt + '</pre>');
The main benefit of using one replace is that it won't need to check the entire string twice. However this does make the code a bit harder to read and possibly to maintain if you need to add/edit which entities you want to replace. So depending on the length of the string to be checked you would need to strike a balance between performance and readability/maintainability.
You may use something like this
var txt = str.replace(/<br ?/?>/g, '\n').replace(/ /g, ' ');
but you can't do 2 replacements using 1 regex
I want to replace a markdown image pattern with the given filename in the textarea with an empty string.
So the pattern is ![alt](http://somehost/uploads/filename.jpg)
This is the code I have now:
var content = target.val();
var fileName = someDynamicValue;
var regex = new RegExp(RegExp.escape('![') + '.*' + RegExp.escape(']') + RegExp.escape('(') + '.*' + RegExp.escape(fileName) + RegExp.escape(')'), 'i');
var found = regex.exec(content);
var newContent = content.replace(regex, "");
target.val(newContent);
RegExp.escape= function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
};
For example var fileName = filename.jpg. Then I need to match ![alt](http://somehost/uploads/filename.jpg) and replace it with an empty string.
Everything works great if the content includes one image. But if there are more then one, for example:
Some text ![alt](http://somehost/uploads/filename.jpg) some text ![alt2](http://somehost/uploads/filename2.jpg) more text.
then var found includes ![alt](http://somehost/uploads/filename.jpg)![alt2](http://somehost/uploads/filename2.jpg), but I need to match only ![alt](http://somehost/uploads/filename.jpg).
What regex I need in this case?
Use non-greedy quantifiers will do:
!\[(.*?)\]\((.*?)\)
You can check it out online: https://regex101.com/r/kfi8qI
Not sure how you are trying to put the strings together but
'.*' is greedily matching up to the last filename.
So, it should probably be '.*?'.
However, if the filenames are different then it shouldn't have matched.
Another thing is you should in general stop it from running past the next [alt] with
something like '[^\[\]]*'
Edit:
RegExp.escape('![') + '.*' + RegExp.escape(']') + RegExp.escape('(') + '.*' + RegExp.escape(fileName) + RegExp.escape(')'), 'i');
is the culprit.
Try
RegExp.escape('![') + '[^\]]*' + RegExp.escape(']') + RegExp.escape('(') + '[^\[\]]*?' + RegExp.escape(fileName) + RegExp.escape(')'), 'i');
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
My input is many lines of text that looks like this:
a.b.c.d.e (f:g)
I need to turn this into
a.b.c.d.e (a/b/c/d/e/f?g)
Note that the dotted part (a.b.c.d.e) can have varying numbers of elements, so sometimes it'll be q.r.s.t, sometimes u.v.w.x.y.z and so on. I have a replace() that will give me (a.b.c.d.e.f?g), but what I need is then to turn all those .s into /s in the result.
Is there a way to do a replace inside a replace? Or should I just call replace() on the string twice?
Sorry if this question is poorly worded, I'm not awfully well versed at regular expressions in javascript.
A very crazy way of doing it:
var str = "a.b.c.d.e (f:g)";
var re = /([^\s]+)\s\(([^:]+):([^\)]+)\)/;
var newStr = str.replace(re, function(a,b,c,d){ return b + " (" + b.replace(/\./g,"/") + "/" + c + "?" + d + ")"; });
jsfiddle
You need to chain the calls to replace() one after the other.
var result = source.replace("foo", "bar").replace("oof", "rab");
A saner way :) http://jsfiddle.net/smfPU/
input = "a.b.c.d.e.w.x.y.z (f:g:h)";
output = input.replace(/:/g, "?");
outputparts = output.split("(");
left = outputparts[0];
middle = left.replace(/\./g, "/").trim();
right = outputparts[1];
output = left + "(" + middle + "/" + right;
document.write(output);