Split String using backslash in javascript - javascript

This is my Temp url and I'm trying to get image name
var str='C:\fakepath\alfa_company.png';
my expected out put like this:
var url='alfa_company.png';

In Javascript "\" has a special meaning.
So, it doesn't get included in your resultant string.
Try
let u = String.raw`C:\fakepath\alfa_company.png`;
u.split("\\")[u.split("\\").length-1]
or
let u = String.raw`C:\fakepath\alfa_company.png`;
u.split("\\").pop()
to understand it better go through How can I use backslashes (\) in a string?

You don't need any jQuery for that :)
const path = 'C:\\fakepath\\alfa_company.png';
const filename = path.split('\\').pop(); // alfa_company.png
You need to use double backlashes because JavaScript treats them as escape characters.

Related

How to replace a multiple patterns in the same string using regex and javascript?

i want to replace multiple patterns in the same string using regex and javascript.
What i am trying to do?
i have a string for example
string = "hello i am [12#fname lname] and i am referring this user [23#fname1 lname1]"
now i get all the strings with [] using regex
const get_strings_in_brackets = string.match(/\[(\d+#[\w\s]+)]/g);
so get_strings_in_brackets will have
["[12#fname lname]", "[23#fname1 lname1]"]
now i want these to be replaced with string "<some-tag id="12"/> "<some-tag id="23"/> in the string "hello i am [12#fname lname] and i am referring this user [23#fname1 lname1]"
also this number 12 in this string "<some-tag id="12"/> is got from the string ["[12#fname lname]" before # character.
What i have tried to do?
i have tried to replace for only one string withing brackets meaning for the example below
string ="hello i am [12#fname lname1]"
const extracted_string_in_brackets = string.match(/\[(\d+#[\w\s]+)]/g);
const get_number_before_at_char =
extracted_string_in_brackets[0].substring(1,
extracted_string_in_brackets[0].indexOf('#'));
const string_to_add_in_tag = `<some-tag
id="${get_number_before_at_char}"/>`;
const final_string = string.replace(extracted_string_in_brackets,
string_to_add_in_tag);
The above code works if i have only one string within square brackets. But how do i do it with multiple strings in brackets and replacing that with tag string that is for example .
Could someone help me solve this. thanks.
Just use a group reference in your replacement:
string = "hello i am [12#fname lname] and i am referring this user [23#fname1 lname1]"
newstr = string.replace(/\[(.+?)#(.+?)\]/g, '<some-tag id="$1"/>')
console.log(newstr)

need regex to get string before and after sepearted by a colon

I am having strings like following in javascript
lolo dolo:279bc880-25c6-11e3-bc22-3c970e02b4ec
i want to extract the string before : and after it and store them in a variable. I am not a regex expert so i am not sure how to do this.
No regex needed, use .split()
var x = 'lolo dolo:279bc880-25c6-11e3-bc22-3c970e02b4ec'.split(':');
var before = x[0]
var after = x[1]
Make use of split(),No need of regex.
Delimit your string with :,So it makes your string in to two parts.
var splitter ="lolo dolo:279bc880-25c6-11e3-bc22-3c970e02b4ec".split(':');
var first =splitter[0];
var second =splitter[1];

Replace single backslash "\" with double backslashes "\\"

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)

escaping quotes from strings using javascript?

For instance say I have the string:
var name = 'Mc'Obrian'
I want to be able to escape the the first quote and the last quote only, not the quote used within the name, how can I achieve this in javascript? thanks
The following will properly escape the single quote given your current code:
var name = 'Mc\'Obrian'
I would encourage you to read the following tutorial about strings. If you are interested in performance considerations, read this question.
use \ to escape the single quote like so:
var name = 'Mc\'Obrian'
var name = 'Mc\'Obrian'
or
var name = "Mc'Obrian"

Replace Characters from string with javascript

I have a string like (which is a shared path)
\\cnyc12p20005c\mkt$\\XYZ\
I need to replace all \\ with single slash so that I can display it in textbox. Since it's a shared path the starting \\ should not be removed. All others can be removed.
How can I achieve this in JavaScript?
You could do it like this:
var newStr = str.replace(/(.)\\{2}/, "$1\\");
Or this, if you don't like having boobs in your code:
var newStr = "\\" + str.split(/\\{1,2}/).join("\\");
You can use regular expression to achieve this:
var s = '\\\\cnyc12p20005c\\mkt$\\\\XYZ\\';
console.log(s.replace(/.\\\\/g, '\\')); //will output \\cnyc12p20005c\mkt$\XYZ\
Double backslashes are used because backslash is special character and need to be escaped.

Categories