I'm trying to do some basic string manipulation on a text variable in Javascript. I have a few lines of code that look like this:
var someVar = 'first+last#domain.com';
var cleanVar = someVar.replace('#','_').replace('+','_');
When I run this code in Chrome's Javascript console, the value of cleanVar is first_last_domain.com... which is as intended. When this code runs on the live page in the browser, the replace() always works for th # character, but never for the +.
To debug this, I've tried swapping positions of the .replace('#','_') with .replace('+','_') and even breaking things out like this:
var someVar = 'first+last#domain.com';
var cleanVar = someVar.replace('#','_');
var cleanVar2 = cleanVar.replace('+','_');
Surely I'm missing something rudimentary here. I know the + combines strings in Javascript... but not when surrounded by quotes, right?
This regex method worked for me:
var cleanVar = someVar.replace(/[+#]/g,'_');
(posted by someone earlier and then removed)
As noted by a commenter, this will replace all instances of # and +. Remove the g to target only the first # or +.
Related
I know RegEx should not be used for parsing HTML, but I'm unable to use any other solution, so I'm stuck with this
I got this for URI.js:
/\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’"e]))/ig
However it doesn't work very well, so I wanted to add a prefix that would search only for strings starting with href=
Ended up with something like this (which works in the RegEx tester):
href\=\"\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’"e]))
But when compiled, it throws "illegal character" error. Not sure if it's the " or = that causes that.
JS code:
matches_temp = result_content.match(href\=\"\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’"e])));
result_content is taken from the DB.
You need the slashes that say this is a regex, sort of how like quotes say that this value is a string. So .match(regex) should be .match(/regex/). Take a look:
var result_content = 'blah';
var matches_temp = result_content.match(/href\=\"\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’"e]))/);
console.log(matches_temp[1]);
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);
First, I'm not sure I've titled my question properly. Please feel free to correct me if needed.
My Issue:
I've created a variable, in jQuery called var siteTitle. This variable is available for other .js files to use and then get passed back to the .html page.
It all works great and there are no issues except when the var siteTitle will contain certain characters that need to be escaped. (quote, single quote, and ampersand to be specific)
What I would like to do is to use a bit of jQuery that would search a particular dom element and see if it is using any of those characters and then automatically escape them.
I've searched for some similar functions and can not seem to find exactly what I need ... the closet idea I have seen is something like this. Its not exactly what I need but it is something like what I am looking for.
pathto: function(path, file) {
var rtrim = function(str, list) {
var charlist = !list ? 's\xA0': (list + '').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
var re = new RegExp('[' + charlist + ']+$', 'g');
return (str + '').replace(re, '');
};
So, I am trying to write a function that will automatically convert those characters to be escaped or their html equivalent.
So, if the var siteTitle is used in a dom element like this:
<h1 class="titleText">' + siteTitle + '</h1>
I need to be able to make sure that any characters get escaped in that element.
Here is a jsFiddle that shows exactly what I am trying to do ...
https://jsfiddle.net/bbyrdhouse/5jb2fdsr/1/
Any help is greatly appreciated.
Since you're using jquery, use the .text() function to set the value into your HTML. It'll escape it appropriately.
var siteTitle = 'My Site "Title"';
$my('.titleText').text(siteTitle);
Also, in your fiddle, the siteTitle variable is not what you think it is, because the 2nd quotation closes that value since it's not yet escaped. I wrapped it in single quotes in my example.
Updated fiddle
Our application needs to process a file path (ie. snip off the last element) which we get in non escaped form c:\blah\di\blah. Unfortunately the backslashes are not escaped, like c:\\blah\\di\\blah, which means that javascript does not really recognise the backslahes; calling a function like indexOf(\\) will return -1.
I have seen countless questions on stackOverflow but I am at a loss on how to proceed.
There is no way we can change the data we get because it is from another framework (extJS),
Is there some way of replacing the single backslashes with \\ ? Then we could process it properly.
I tried :
str.replace(/\/, "\\\\");
str.replace(/\/g, "\\\\"); mentioned here.
str.replace(String.fromCharCode(92),String.fromCharCode(92,92)); mentioned here
str.replace("\\", "\\\\");
escape() function mentioned here. This gives me c%3A%08lahdi%08lah
In the same question this looked promising: var justTheName = str.split(String.fromCharCode(92)).pop(); But also does not work for me.
I have a fiddle with this code :
var str = 'c:\blah\di\blah'
str = str.replace(/\\/, "\\\\");
alert('' + str)
I am trying to some some urls throught javascript where some replacement of urls needs to be done. I have a textarea with some URLs example given below:
http://mywebsite.com/preview.aspx?mode=desktop&url=http://mywebsite.com/post.aspx?id=44&content=1
http://mywebsite.com/preview.aspx?mode=desktop&url=http://mywebsite.com/post.aspx?id=44&content=2
http://mywebsite.com/preview.aspx?mode=desktop&url=http://mywebsite.com/post.aspx?id=44&content=3
http://mywebsite.com/preview.aspx?mode=desktop&url=http://mywebsite.com/post.aspx?id=44&content=3
Now what i am trying to do is replacing http://mywebsite.com/preview.aspx?mode=desktop&url= with spaces.
I have tried using str.replace() but it is replacing only first occurence of that url.
I have also tried with Global variable g the query i have used is
str_replace(\http://mywebsite.com/preview.aspx?mode=desktop&url=/g,'');
But its not working So can anyone tell me how i can do that ?
I want the output of the textarea like:
http://mywebsite.com/post.aspx?id=44&content=1
http://mywebsite.com/post.aspx?id=44&content=2
http://mywebsite.com/post.aspx?id=44&content=3
http://mywebsite.com/post.aspx?id=44&content=4
I believe that your biggest issue is that your regex syntax is incorrect. Try this:
Imagine that var s is equal the the value of your textarea.
s.replace(/http\:\/\/mywebsite\.com\/preview.aspx\?mode\=desktop\&url\=/g, '');
The issue you were having was improper delimiters and unescaped reserved symbols.
Though Javascript has some of its own regex idiosyncrasies, the issues here were related to basic regex, you might find these resources useful:
http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/
http://regexpal.com
try this.
var string = document.getElementById('textareaidhere');
string.replace(/http:\/\/mywebsite\.com\/preview\.aspxmode=desktop&url=/g, '');
JSFiddle here