Javascript: replace inside a replace - javascript

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);

Related

adding float in jquery

var sssee = "581.30";
var ssser = "1,178.70";
var ssee = sssee.trim().replace(/,/g, "");
var sser = ssser.trim().replace(/,/g, "");
console.log("ee " + ssee)
console.log("er " + sser)
console.log("total " + parseFloat(ssee + sser))
In log i see:
ee 581.30
er 1178.70
total 581.301178
Why is it when adding replace to remove the , messes the computation.
Variables ssee and sser are both strings. When you peform ssee + sser it would return string 581.301178.70 which would be passed to parseFloat function then. When there are two decimal points, only first is taken as correct, that's why parseFloat returns 581.301178.
Check the snippet with correct solution.
var sssee = 581.30;
var ssser = "1178.70";
var ssee = String(sssee).trim().replace(/,/g, "");
var sser = String(ssser).trim().replace(/,/g, "");
console.log("ee " + ssee)
console.log("er " + sser)
console.log("total " + (parseFloat(ssee) + parseFloat(sser)))
You should also wrap ssee and ssser in String object before using trim and replace methods. Without doing that if you provide those variables as floats, instead of strings, your code won't work.
Your problem:
You concatenate two strings ("581.30" + "1,178.70") to one string ("581.301178.70"). Then you parse it to a float (581.301178).
Solution:
You need to parse each one to a float at first. After do your addition (parseFloat(ssee) + parseFloat(sser)).

Javascript splitting string in to two parts number and text safely

I was wondering if there is a safe way (if the data is coming from users) to get the string and the number separated - for example "something-55", "something-124", "something-1291293"
I would want:
something and
55
something and
124
something and
1291293
I mean by a 'safe way' is to be certain I am getting only the number on the end.. if the data is coming from the users "something" could be anything some-thing-55 for example..
I'm looking for a robust way.
try this, working.
var string = 'something-456';
var array = string.split('-');
for (var i = 0;i<array.length;i++){
var number = parseFloat(array[i]);
if(!isNaN(number)){
var myNumber = number;
var mySomething = array[i - 1];
console.log('myNumber= ' + myNumber);
console.log('mySomething= ' + mySomething);
}
}
Can you try this?
var input='whatever-you-want-to-parse-324';
var sections=input.split(/[\w]+-/);
alert(sections[sections.length-1]);
You can use substr along with lastIndexOf:
var str = "something-somethingelse-55",
text = str.substr(0, str.lastIndexOf('-')),
number = str.substr(str.lastIndexOf('-') + 1);
console.log(text + " and " + number);
Fiddle Demo
All though it's a tad late, this would be the most restrictive solution:
var regex = /^([-\w])+?-(\d+)$/,
text = "foo-123",
match = test.match(regex);
You will get a match object back with the following values:
[ "foo-123", "foo", "123" ]
It's a very strict match so that " foo-123" and "foo-123 " would not match, and it requires the string to end in one or more digits.

Regex to match markdown image pattern with the given filename

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');

Replace first occurance of char with * then the rest with a ' '

I have a sentence (this is a dumb example sentence ) that looks like this:
I_like_to_program__.
I need a function to make it look like this:
I*like to program.
I have written this expression:
var myExpression = new RegExp("\\_", "g");
return myString.replace(myExpression, " ").trim();
That'll output: "I like to program." --I'm close. I just need the first space to replace with a * to make it look like I*like to program.
mystring.replace("_", "*")
.replace(/_/g, " ");
Or you could avoid the regex altogether like this:
mystring.replace("_", "*")
.split("_")
.join(" ");
If you don't add g, javascript's replace default to only one replacement :
return myString.replace(/\__/, "").replace(/\_/, "*").replace(/\_/g, " ");
var myString = "I_like_to_program__.";
var result = myString.replace(/\_/g, " ").replace(" ", "").replace(" ", '*');
alert(result);
The easiest thing I can think of is to do it in two steps-- replace the first instance with *, then iterate again and replace globally with " "
var myString = "I_LIKE_TO_PROGRAM";
var myExpression = new RegExp("\_");
myString = myString.replace(myExpression, "*").trim();
var newExpression = new RegExp("\_", "g");
alert(myString.replace(newExpression, " ").trim());
I first replace all _ replace with "", after doing this in we we will have program .
So In second replace I am removing (program .) this space and in third replace I put * in first place.
DEMO
http://jsfiddle.net/saorabhkr/QV9qH/

replace space with dash JavaScript

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>

Categories