I have a problem with the .split() function , I have the following string:
var imageUrl = "Images\Products\randomImage.jpg";
And I want to split by the character "\", but, this happens:
//If dont use double "\\", throws me an error.
var imageUrlArray = imageUrl.split("\\");
Then the variable has this value:
"ImagesProductsrandoImage.jpg"
I need to do that, because need to change this "\" into "/", because makes me an error with a plugin. The original String is obtained from the DataBase.
The first \ is escaping the second \ character. Your string should also be doubled up.
var imageUrl = "Images\\Products\\randomImage.jpg";
var updated = imageUrl.replace(/\\/g,"/");
console.log(updated);
You need to escape the file string so that the backslashes there become "\", then you can preform your split, and then un-escape the resulting array of strings for other characters that may have been backslashed.
Not too familiar with Javascript but it probably looks something like this:
$fileName = escape($fileName)
Related
I am hoping to get some insight into this issue I am having. I couldn't really find any other questions like this doing the same thing. I am using python 3.7.
I am pulling in contents of strings using regex which then will replace other parts of a JavaScript file I am reading in. I am familiar with raw strings when reading data in, but when I go to replace certain parts containing the double backslash only one is printed. I know it is escaping the string due to the backslash on the \", but I am at a loss with this. Adding a third "\" to it making it "\\\" will solve the issue, but I cannot do that due to the type of data I am working with.
For example, I want to replace all instances that the string "Ch" is found in a file I am reading in with "\\" using regex. This new data is then outputted to a new file.
How do I go about replacing certain content with the string '"\\"' ensuring that nothing is escaped and only "\\" is outputted?
Simplified sample code for testing:
string = R'"\\"'
Converted_Text = re.sub("Ch", ' ' + string, Converted_Text)
with open('output.js','w') as w:
w.write(Converted_Text.strip().replace('\n',''))
Sample file being read in:
var test = Ex("Temp") + Ch + wn;
var num1= 1;
var num2 =2;
var sum = num1+num2;
var blah, meh;
You can first replace CH with \\CH and again replace CH with \\.
How can we split the following tag to extract the substring "PDSGJ:IO.HJ".
var input = "\\initvalues\PDSGJ:IO.HJ~some" .
I tried the following:
var input = "\\initvalues\PDSGJ:IO.HJ~some";
var b = input.split('\\');
alert(b[1]);
Note: The format remains the same , \\,\, ~ format is same and mandatory for all strings .
But the problem is , I get the output as: initvaluesPDSGJ:IO.HJ~some.
I need '\' also because I need to further split and get the value.
Any other method is there to get the value?
You can use regular expressions:
var input = '\\initvalues\PDSGJ:IO.HJ~some',
b = input.match(/[A-Z]+:[A-Z]+.[A-Z]+~[a-z]+/);
console.log(b && b[0]);
The backslash is interpreted as an escape character. So you're gonna have to add another backslash for each backslash.
Then directly search for the last backslash and then slice the string:
var input = "\\\\initvalues\\PDSGJ:IO.HJ~some";
var index = input.lastIndexOf('\\');
var str = input.slice(index+1)
alert(str);
It is indeed correct, like the others already mentioned, that a backslash is interpreted as an escape character.
To output proper result, thus as a list.
var txt='\\\\initvalues\\PDSGJ:IO.HJ~some';
txt.split(/\\\\/).pop(0).split(/\\/)
(2) ["initvalues", "PDSGJ:IO.HJ~some"]
I Need to replace a set of characters from a string, I don't have control over the string so I can't just escape the + symbol inside the string.
So my question is, seeing as this works if I change my value to 'breeding' it does replace the string. How can I escape a string without manually escaping them? I have tried
var s = "http://example.co/kb/tags/anazolic~racing~all+articles~breeding";
var value = 'all+articles';
var find = new RegExp('\~?\\b' + value + '\\b', 'g');
var l = s.replace(find, '');
console.log(l);
DEMO: http://jsfiddle.net/AnBc6/1/
I have also tried adding: value = encodeURIComponent(value); but this didn't work either.
Any Help?
So, if I understand correctly, you want to escape special regex characters.
value = value.replace(/[-\\()\[\]{}^$*+.?|]/g, '\\$&');
You could extract this to a function of course:
function escapeRegex(value) {
return String(value).replace(/[-\\()\[\]{}^$*+.?|]/g, '\\$&');
}
Change the third line to this:
var find = new RegExp('\~?\\b' + value.replace(/\+/g,'\\+') + '\\b', 'g');
The plus sign is a special character in a Regular Expression, so it needs to be escaped with a backslash.
(Also, I'm not sure what you mean by "stored in a variable." Everything in JavaScript is "in a variable." Or maybe you really mean, "stored in a RegExp object.")
I have string with file path. I want to replace all single backslashes ("\") with double backslashes ("\\").
var replaceableString = "c:\asd\flkj\klsd\ffjkl";
var part = /#"\\"/g;
var filePath = replaceableString .replace(part, /#"\\"/);
console.log(filePath);
Console showed me it.
c:asdlkjklsdfjkl
I found something like this, unfortunately it didn't work.
Replacing \ with \\
Try:
var parts = replaceableString.split('\\');
var output = parts.join('\\\\');
Personally, as I am not so expert in reg exps, I tend to avoid them when dealing with non-alphanumeric characters, both due to readability and to avoid weird mistake.
var replaceableString = "c:\asd\flkj\klsd\ffjkl";
alert(replaceableString);
This will alert you c:asdlkjklsdfjkl because '\' is an escape character which will not be considered.
To have a backslash in your string , you should do something like this..
var replaceableString = "c:\\asd\\flkj\\klsd\\ffjkl";
alert(replaceableString);
This will alert you c:\asd\flkj\klsd\ffjkl
JS Fiddle
Learn about Escape sequences here
If you want your string to have '\' by default , you should escape it .. Use escape() function
var replaceableString = escape("c:\asd\flkj\klsd\ffjkl");
alert(replaceableString);
JS Fiddle
You have several problems in your code.
To get a \ in your string variable you need to escape it.
When you create a string like this: replaceableString = "c:\asd\flkj\klsd\ffjkl"; characters with a \ before are treated as escape sequences. So during the string creation, it tries to interpret the escape sequence \a, since this is not valid it stores the a to the string. E.g. \n would have been interpreted as newline.
I assume the # is coming from a .net example. Javascript does not know "raw" strings.
remove the quotes from your regex.
This would do what you want:
var string = "c:\\asd\\flkj\\klsd\\ffjkl";
var regex = /\\/g;
var FilePath = string.replace(regex, "\\\\");
Here is the answer:
For replacing single backslash with single forward slash:
var stringReplaced = String.raw`c:\asd\flkj\klsd\ffjkl`.split('\\').join('/')
console.log(stringReplaced);
For replacing double backslash with single forward slash:
var stringReplaced = String.raw`c:\\asd\\flkj\\klsd\\ffjkl`.split('\\\\').join('/')
console.log(stringReplaced);
\ is a escape character. Therefore replaceableString does not contain any backslashes.
To fix this you should declare the string like this:
var replaceableString = "c:\\asd\\flkj\\klsd\\ffjkl";
First encode the string
then replace all occurrences of %5C with %5C%5C
At the end decode the string
var result = encodeURI(input);
result=decodeURI(result.replace(/%5C/g,"%5C%5C"));
If you have no control over the contents of the string you are trying to find backslashes in, and it contains SINGLE \ values (eg. variable myPath contains C:\Some\Folder\file.jpg), then you can actually reference the single backslashes in JavaScript as String.fromCharCode(92).
So to get the file name in my filepath example above.
var justTheName = myPath.split(String.fromCharCode(92)).pop();
In case of string matching, it is better to use encodeURIComponent, decodeURIComponent.
match(encodeURIComponent(inputString));
function match(input)
{
for(i=0; i<arr.length; i++)
{
if(arr[i] == decodeURIComponent(input))
return true;
else return false;
}
}
In the case of a single back slash in the string, the javascript replace method did not allow me to replace the single back slash.
Instead I had to use the split method which returns an array of the split strings and then concatenate the strings without the back slash (or whatever you want to replace it with)
Solution (replaced backslash with underscore):
var splitText = stringWithBackslash.split('\\');
var updatedText = splitText[0] + '_' + splitText[1];
You need to pass to pass value of a string through String.raw before you assign value to a variable.
var replaceableString = String.raw`c:\asd\flkj\klsd\ffjkl`.replace(/\\/g,"\\\\");
console.log(replaceableString)
Any working Regex to find image url ?
Example :
var reg = /^url\(|url\(".*"\)|\)$/;
var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';
var string2 = 'url(http://domain.com/randompath/random4509324041123213.jpg)';
console.log(string.match(reg));
console.log(string2.match(reg));
I tied but fail with this reg
pattern will look like this, I just want image url between url(" ") or url( )
I just want to get output like http://domain.com/randompath/random4509324041123213.jpg
http://jsbin.com/ahewaq/1/edit
I'd simply use this expression:
/url.*\("?([^")]+)/
This returns an array, where the first index (0) contains the entire match, the second will be the url itself, like so:
'url("http://domain.com/randompath/random4509324041123213.jpg")'.match(/url.*\("?([^")]+)/)[1];
//returns "http://domain.com/randompath/random4509324041123213.jpg"
//or without the quotes, same return, same expression
'url(http://domain.com/randompath/random4509324041123213.jpg)'.match(/url.*\("?([^")]+)/)[1];
If there is a change that single and double quotes are used, you can simply replace all " by either '" or ['"], in this case:
/url.*\(["']?([^"')]+)/
Try this regexp:
var regex = /\burl\(\"?(.*?)\"?\)/;
var match = regex.exec(string);
console.log(match[1]);
The URL is captured in the first subgroup.
If the string will always be consistent, one option would be simply to remove the first 4 characters url(" and the last two "):
var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';
// Remove last two characters
string = string.substr(0, string.length - 2);
// Remove first five characters
string = string.substr(5, string.length);
Here's a working fiddle.
Benefit of this approach: You can edit it yourself, without asking StackOverflow to do it for you. RegEx is great, but if you don't know it, peppering your code with it makes for a frustrating refactor.