How to replace a backslash character with a semicolon? - javascript

I'm trying to do a simple replace of a backslash occurence in a string. So I used the string.replace method, passing in a regex for the backslash to be removed \.
But I noticed when I invoke this method, instead of replacing the backslash after EMEA with a colon : character. It just removes the first letter in the username.
I've made a JSFIddle of the code here.
Not sure why the regex doesn't work as it's suggested in other SO answers here:
Replace all backslashes in a string with a pipe
Question:
How can you replace a backslash character with a semicolon?
Code gist:
var str = "EMEA\victorb";
str = str.replace(/\\/g, ':');
document.write(str);

That's a problem with the original string, not with the regex: it's
var str = "EMEA\victorb";
When it shold be:
var str = "EMEA\\victorb";

var str = "EMEA\\victorb";
str = str.replace("\\", ':'); because if you let just one \ it will be ignored.

Related

Replace substring which contains backslash using RegExp function javascript

I am trying to write a function which replaces certain words with abbreviations. For example I have the string:
str="Calculate $2\\cdot 2$"
in which I want to replace
"\\cdot"
with
"*"
My code looks like this:
str = str.replace(RegExp("\\cdot",'g'),"*");
And the result is
str = "Calculate $2\\cdot 2$"
And I need to use the RegExp function because I have a whole list of words which I want to replace with abbreviations. I know that
str = str.replace(/\\cdot/g),"*");
works. But I don't understand why RegExp doesn't.
You need to escape the slash character when defining a String and once again for the regular expression. If you just escape the slash once in a String, the resulting regex would like this: \cdot. If you define the regular expression directly with the slash notation (/regex/), you would only need to escape it once, because there is no String.
var str = "Calculate $2\\cdot 2$";
str = str.replace(RegExp("\\\\cdot",'g'),"*");
console.log(str);
If you want to generically prepend all the regex special characters with a slash, you can use the following solution, which relies on this answer. You still have to escape the backslash once, because it is part of a String. If you get your String from somewhere, it will be correctly escaped. It's only necessary, if you explicitly write the String into the code (var string = "string";).
var str = "Calculate $2\\cdot 2$";
var regex = "\\cdot";
str = str.replace(RegExp(escapeRegExp(regex), 'g'),"*");
console.log(str);
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

how to replace the forward slash to backslash and forward slash using javascript

I want to replace the "/" into "\/" using javascript.
for example:
http://www.freeformatter.com/javascript-escape.html
to
http:\/\/www.freeformatter.com\/javascript-escape.html
You can do:
str.replace(/\//g, "\\/");
where str is the variable that holds the string value.
Demo: http://jsbin.com/zijaqo/1/edit?js,console
use replace:
"http:/www.freeformatter.com/javascript-escape.html".replace(/\//g, "\\/");
If you have the string in a variable:
var url = "http:/www.freeformatter.com/javascript-escape.html";
url.replace(/\//g, "\\/");
You could use str.replace() and a Regular expression object here. Basically you just need to escape the escape character in your replacement string.
str = str.replace(new RegExp('/','g'),"\\/");

Regex for both newline and backslash for Replace function

I am using a replace function to escape some characters (both newline and backslash) from a string.
Here is my code:
var str = strElement.replace(/\\/\n/g, "");
I am trying to use regex, so that I can add more special characters if needed. Is this a valid regex or can someone tell me what am I doing wrong here?
You're ending the regex early with an unescaped forward slash. You also want to use a set to match individual characters. Additionally you might want to add "\r" (carriage return) in as well as "\n" (new line).
This should work:
var str = strElement.replace(/[\\\n\r]/g, "");
This is not a valid regex as the slash is a delimiter and ends the regex. What you probably wanted is the pipe (|), which is an alternation:
var str = strElement.replace(/\\|\n/g, "");
In case you need to extend it in the future it may be helpful to use a character class to improve readability:
var str = strElement.replace(/[\\\nabcx]/g, "");
A character class matches a single character from it's body.
This should work. The regular expression replaces both the newline characters and the backslashes in escaped html text:
var str = strElement.replace(/\\n|\\r|\\/g, '');

how to replace backslash character with double backslash in javascript?

I'm trying to replace backslashes in my string with two backslashes like so:
s = s.replace("\\", "\\\\");
But, it doesn't do anything. Example string:
s="\r\nHi\r\n";
The string doesn't contain a backslash, it contains the \r escape sequence.
Working example
For example
var str = "\r\n";
var replaced = str.replace('\r\n', '\\r\\n');
alert(replaced);
Then the alert will be shown \r\n

RegEx that will match the last occurrence of dot in a string

I have a filename that can have multiple dots in it and could end with any extension:
tro.lo.lo.lo.lo.lo.png
I need to use a regex to replace the last occurrence of the dot with another string like #2x and then the dot again (very much like a retina image filename) i.e.:
tro.lo.png -> tro.lo#2x.png
Here's what I have so far but it won't match anything...
str = "http://example.com/image.png";
str.replace(/.([^.]*)$/, " #2x.");
any suggestions?
You do not need a regex for this. String.lastIndexOf will do.
var str = 'tro.lo.lo.lo.lo.lo.zip';
var i = str.lastIndexOf('.');
if (i != -1) {
str = str.substr(0, i) + "#2x" + str.substr(i);
}
See it in action.
Update: A regex solution, just for the fun of it:
str = str.replace(/\.(?=[^.]*$)/, "#2x.");
Matches a literal dot and then asserts ((?=) is positive lookahead) that no other character up to the end of the string is a dot. The replacement should include the one dot that was matched, unless you want to remove it.
Just use special replacement pattern $1 in the replacement string:
console.log("tro.lo.lo.lo.lo.lo.png".replace(/\.([^.]+)$/, "#2x.$1"));
// "tro.lo.lo.lo.lo.lo#2x.png"
You can use the expression \.([^.]*?):
str.replace(/\.([^.]*?)$/, "#2x.$1");
You need to reference the $1 subgroup to copy the portion back into the resulting string.
working demo http://jsfiddle.net/AbDyh/1/
code
var str = 'tro.lo.lo.lo.lo.lo.zip',
replacement = '#2x.';
str = str.replace(/.([^.]*)$/, replacement + '$1');
$('.test').html(str);
alert(str);​
To match all characters from the beginning of the string until (and including) the last occurence of a character use:
^.*\.(?=[^.]*$) To match the last occurrence of the "." character
^.*_(?=[^.]*$) To match the last occurrence of the "_" character
Use \. to match a dot. The character . matches any character.
Therefore str.replace(/\.([^\.]*)$/, ' #2x.').
You could simply do like this,
> "tro.lo.lo.lo.lo.lo.zip".replace(/^(.*)\./, "$1#2x");
'tro.lo.lo.lo.lo.lo#2xzip'
Why not simply split the string and add said suffix to the second to last entry:
var arr = 'tro.lo.lo.lo.lo.lo.zip'.split('.');
arr[arr.length-2] += '#2x';
var newString = arr.join('.');
'tro.lo.lo.lo.lo.lo.png'.replace(/([^\.]+).+(\.[^.]+)/, "$1.#x2$2")

Categories

Resources