Escape string characters without manually escaping them - javascript

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.")

Related

Regular expression when reading files javascript

I have a situation where I have 3 font files and I read its content in order to find mathes with font name. But the thing is that font names are Wingdings, Wingdings 2, Wingdings 3. And when I have Wingdings font name it matches all 3 files, but I need file that exactly is associated with font name, not all 3 of them. I tried to find it using indexOf method, but it didn't help. The only rational way is to use regular expression, but cannot think of a right one. One more thing need to be mentioned is that I have to pass a parameter into that regExp, something like
var regExp = new RegExp('\\^' + fontName + '$\\', 'g');
if (currentFileContent.search(regExp) !== -1) {...}
Any help will be greatly appreciated.
It seems you try to use regex delimiters in a RegExp constructor. You only need /.../ in the literal notation.
Note you need not escape the start and end of string anchors, they lose their special meaning in the regex then. \\ matches a single \, but it cannot be matched after end of string ($).
Also, you can use RegExp#test() function to check if the string matches the pattern (note no g modifier can be used with it):
var regExp = RegExp('^' + fontName + '$');
if (regExp.test(currentFileContent)) { ... }
If font names contain special characters, use escapeRegExp function from MDN:
function escapeRegExp(string){
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
And then
var regExp = RegExp('^' + escapeRegExp(fontName) + '$');
And the final note: if the font names appear inside a larger string, and you need to match Windings but not Windings3, use
var regExp = RegExp('\\b' + escapeRegExp(fontName) + '\\b');
The \b is a word boundary.
UPDATE
To make sure you only match a font name that is not followed by a whitespace (if any) and a digit, use a (?!\\s*\\d) lookahead when declaring a RegExp:
var fontName = "Wingding";
var contents = "Font name: Wingding, the other file: Font name: Wingding 2. And so forth. ";
var rExp = RegExp(fontName + '(?!\\s*\\d)');
if (rExp.test(contents)) {
document.write(fontName + " was found in '<i>" + contents + "</i>'.");
}

Regarding double escaping characters when using regexp constructor with a string to make a regexp

In Javascript, I want to match a string pattern that goes something like:
\left((some expression here to be matched)\right)
It's a little more complicated than that, so I have to define my pattern using the RegExp constructor. The simplified version is:
var pattern_string = '\\left\\((' + EXPRESSIONpattern + ')\\\\right\\)' ;
var pattern_regexp = new RegExp(pattern_string, 'g');
I realize that \r is the carriage return character in a string, hence having the four back slashes in the pattern_string before the r. Upon implementing, the only way I could get it to work was to also treat \l as a special string character and use:
var pattern_string = '\\\\left\\((' + EXPRESSIONpattern + '\\\\right\\)' ;
var pattern_regexp = new RegExp(pattern_string, 'g');
Why do I need to double escape the l? I can't find a reference that says \l is a special string sequence. What does \l mean in a string? Can someone point me to a reference that includes all characters that need to be double escaped in a string? It would help greatly with debugging to know for sure when I need to double escape.
Thanks in advance for your help,
T

How to remove the special characters from a string using javascript

I have the below String value to be displayed in text area and i want to remove the first characters ##*n|n from the string .
The string is as follows :
Symbol-001
##*n|nClaimant Name
##*n|nTransaction
I have used the below code to deal with removing the special characters
var paramVal1 = parent.noteText; //paramVal1 will have the string now
var pattern = /[##*n|n]/g;
var paramVal1 = paramVal1.replace(pattern,'');
document.getElementById("txtNoteArea").value = paramval1;//appending the refined string to text area
For the above used code am getting the out put string as below
Symbol-001
|Claimat Name //here 'n' is missing and i have an extra '|' character
|Transactio //'n' is missing here too and an extra '|' character
Kindly help to remove the characters ##*n|n without affecting the other values
What your regex is saying is "remove any of the following characters: #|*n". Clearly this isn't what you want!
Try this instead: /##\*n\|n/g
This says "remove the literal string ##*n|n". The backslashes remove the special meaning from * and |.
You are using regular expression reserved chars in your pattern, you need to escape them
You can use this expression:
var pattern = /[\#\#\*n\|n]/g;
i think use this /[##*n\|n]/g regEx
If you want to replace the first occurrence as you say on your question, you don't need to use regex. A simple string will do, as long as you escape the asterisk:
var str = "Symbol-001 ##*n|nClaimant Name ##*n|nTransaction";
var str2 = str.replace("##\*n|n", ""); //output: "Symbol-001 Claimant Name ##*n|nTransaction"
If you want to replace all the occurrences, you can use regex, escaping all the characters that have a special meaning:
var str3 = str.replace(/\#\#\*n\|n/g, ""); //output: "Symbol-001 Claimant Name Transaction"
Have a look at this regex builder, might come in handy - http://gskinner.com/RegExr/

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)

Javascript search and replace sequence of characters that contain square brackets

I'm trying to search for '[EN]' in the string 'Nationality [EN] [ESP]', I want to remove this from the string so I'm using a replace method, code examaple below
var str = 'Nationality [EN] [ESP]';
var find = "[EN]";
var regex = new RegExp(find, "g");
alert(str.replace(regex, ''));
Since [EN] is identified as a character set this will output the string 'Nationality [] [ESP]' but I want to remove the square brackets aswell. I thought that I could escape them using \ but it didn't work
Any advice would be much appreciated
Try setting your regex this way:
var regex = /\[EN\]/g;
If you just want to replace a single instance of it you can just str = str.replace("[EN] ", ""); otherwise; var find = "\\[EN\\]";.

Categories