how do i replace \ character? - javascript

i got the following code
replaceforever: function(string,find,replace){
while(_.contains(string,find)){
string.replace(find,replace);
}
return string;}
and i am sending to it something like './routes\admin\articles.js','\\','/'
but it always seem to enter the while loop once and change it all with one '/' as result :|
instead of being a nice ./routes/admin/articles.js
can anyone explain to me please what am i doing wrong?

The problem is with your testing, not with the code (assuming you are using underscore.js;
using regular expressions would be more sensible).
You need to escape your backslashes in the input string:
replaceforever('./routes\\admin\\articles.js','\\','/');
'./routes\admin\articles.js', on the other hand, evaluates to './routesadminarticles.js'.

If I get it right, this will do a global replacement:
stringVariable.replace(/\\/g, '/');

I think the problem is actually that your while-loop isn't being entered at all, rather than that it's being entered once. Note that your input actually already has a /, and I think that's what you're seeing.
This line:
string.replace(find,replace);
creates a new string with the specified replacement . . . and then throws it away. So if your while-loop were being entered even once, it would actually be an infinite loop, because the loop body doesn't actually do anything. Instead, you need to store the result in the variable string:
string = string.replace(find,replace);
But I'm not sure this method is really a good idea anyway. JavaScript already offers "replace-all" functionality, using regexes:
result = input.replace(/\\/g, '/');

First: string.replace() will replace ALL the matches, so there is no need of iteration :)
Second: string.replace() will return a NEW string, it wont change the object used.
So you need something like:
replaceforever: function (string,find,replace) {
return string.replace(find,replace);
}

Related

How do you sanitize a string to pass a regex?

I have a regex validation I need my string to pass.
/^[0-9a-zA-Z-]+$/
I want to create a function that sanitizes the string for it to pass the regex.
I thought of doing something like
string.replace(/^[0-9a-zA-Z-]+$/,"");
Except I need to invert the above regex.
I tried to look up how to invert a regex but nothing seems to show up.
Try this string.replace(/\W/g,""). Also check this web site i always use it to test regular expressions, it also has hints on the right bottom
Negate the collection using ^ inside the []
const str = `abc*รง%ABC&(/())12345=?`
const newString = str.replace(/[^0-9a-zA-Z-]/g,"");
console.log(newString)

Why isn't .replace() working on a large generated string from escodege.generate()?

I am attempting to generate some code using escodegen's .generate() function which gives me a string.
Unfortunately it does not remove completely the semi-colons (only on blocks of code), which is what I need it to do get rid of them myself. So I am using the the .replace() function , however the semi-colons are not removed for some reason.
Here is what I currently have:
generatedCode = escodegen.generate(esprima.parseModule(code), escodegenOptions)
const cleanGeneratedCode = generatedFile.replace(';', '')
console.log('cleanGeneratedCode ', cleanGeneratedCode) // string stays the exact same.
Am I doing something wrong or missing something perhaps?
As per MDN, if you provide a substring instead of a regex
It is treated as a verbatim string and is not interpreted as a regular expression. Only the first occurrence will be replaced.
So, the output probably isn't exactly the same as the code generated, but rather the first semicolon has been removed. To remedy this, simply use a regex with the "global" flag (g). An example:
const cleanGenereatedCode = escodegen.generate(esprima.parseModule(code), escodegenOptions).replace(/;/g, '');
console.log('Clean generated code: ', cleanGeneratedCode);

.trim() and regular expressions producing unexpected results

I wrote a fairly simple regular expression to detect when a string looks like it could be an email:
var looksLikeEmail = /^\S+#\S+\.\S+$/gi;
I'm using Knockout and the string being tested is the value of a textarea.
Essentially, say we have the value of the textarea in a variable text. This value was, for example, the typed in value abc#example.com.
What's odd, is it seems like, even though text === text.trim(), looksLikeEmail.test(text) returns true, but looksLikeEmail.test(text.trim()) returns false.
On the other hand, if I manually create the string var test2 = 'abc#example.com', it does not have this issue.
This seems to indicate to me that the textarea is inserting some odd characters or something... that .trim() is doing something weird with. But test.length === test2.length and test.length === test.trim().length
Does anyone know how to make this behave correctly?
I've written up a jsfiddle to quickly demonstrate the behavior...
If you go to the fiddle and try typing in an email... you will see the problem. another weird behavior: add a space after the email, then remove it. /confused
Any help is much appreciated. Thanks.
.test(), just like .exec() will remember the last index of a match when using a global regex, and try to match from it onward, failing on the second call. Just remove the /g option from your regex - it doesn't make sense to have /g in a non-multiline regex which matches beginning and end.

Single Quote in Javascript Param

I have a function that, when clicked, fills in a field of the parent window. In this case, it's a name (text) field.
The problem I'm having is if the field has a single quote in it (ex. Bill's Chili) the function fails because it reads the single quote as the end of the parameter.
Here is the call:
href="javascript:selectItem('recipe','recipe_name','<recipe_description')"
Again, if the name is Bill's Chili, it causes a syntax error.
Is there a way to automatically convert that single quote to the HTML equivalent so it will read properly?
Thanks
For the single quotes in the field use \' More info on escape characters here.
href="javascript:selectItem('Bill\'s Chilli','recipe_name','<recipe_description')"
The answer I found was completely different than I thought. The page itself is written is ASP (Sorry I forgot to mention that, I didn't think it mattered since the function was javascript and it was called in HTML).
Therefore, I just used this:
<%fixed_name = Replace(recipe_name,"'","") %>
And then used fixed_name instead of recipe_name in the function call.
Thanks for all your help, it set me in the right direction!
try this
href='javascript:selectItem("recipe","recipe_name","<recipe_description")'
You may try to use escaped 'double' quote like that:
href="javascript:selectItem(\"recipe\",\"recipe_name\",\"recipe_description\")"
Please let me know whether it works.
You could use str.replace
Just remplace " by " et ' by ' . :)
But actually, I'm assuming you're getting all of that stuff from a php script (from some sort of storage), in which case you could escape the quotes directly with php, that would be way more safer.

jquery or javascript trim or substr

var str='userkwd* type:"Office"';
How do I trim or substr or slice this string to only get 'userkwd'? Also the variable will have quotes as part of it..This one is tricky as if there is no userkwd .i.e. if
var str=' type:"Office"';
it should return null. The * gets appended with userkwd from inputbox..
str.slice(0,str.indexOf('*')); ???
str.split("*")[0]; ????
str.substring(0, str.indexOf('*')); ???
Which one?
str.replace(/\*? type.*/, '');
The answer is trivial. Think if userkwd can contain " ", for example "user kwd". If so, then you cannot use split(" "). If userkwd could contain additional * like user*kwd then you cannot use this character. If the keyword could contain both spaces and * then you should use different method, for example some more complicated regular expression, but try to evalute your suggested methods first.
By the way, in the scenario you have given var str=' type:"Office"'; there is no userkwd at all, there is also no *, so you definitely should not use * if this is valid example. Space seaprator however holds, so I would go for it if possible.
You can also try to find the last occurance of "type:" and get everything what is before it, if empty then change it to null, or something like this. There are really a lot of possibilities, we do not have enough information why you need this functionality and what could be the input...

Categories