I'm having this problem with the apostrophe ("'") in JS. I'm using the encodeURIComponent() to encode this and then replace the (') with (%27) as follows.
var request = encodeURIComponent(requestString).replace("'", "%27");
But if the apostrophe is with a bracket, the apostrophe wont get replaced.
ex: (")'")
("')")
("('")
Even when the apostrophe is followed by a numeric number it wont get replaced.
Is there a solution for this?
Thanks in advance.
Nilushi
String.replace method accepts a string or regular expression as its first parameter. When a string is passed as the first parameter, only the first match is replaced:
"'''''".replace("'", "%27"); // "%27''''"
You should use a regular expression instead along with the g flag; which replaces ALL matches:
"'''''".replace(/'/g, "%27"); // "%27%27%27%27%27"
You need to specify /g global modifier:
var request = encodeURIComponent(requestString).replace(/'/g, "%27");
Example:
var str = "(''')";
var request = encodeURIComponent(str).replace(/'/g, "%27");
console.log(request); // (%27%27%27)
Related
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 want to remove size data from a file name like
var src = 'http://az648995.vo.msecnd.net/win/2015/11/Halo-1024x551.jpg';
src = src.replace(
/-\d+x\d+(.\S+)$/,
function( match, contents, offset, s ) {
return contents;
}
);
this works as expected and i get
http://az648995.vo.msecnd.net/win/2015/11/Halo.jpg
But if I have a filename like
http://az648995.vo.msecnd.net/win/2015/11/slot-Drake-08-2000x1000-1024x512.jpg
it returns
http://az648995.vo.msecnd.net/win/2015/11/slot-Drake-08-1024x512.jpg
instead of the desired
http://az648995.vo.msecnd.net/win/2015/11/slot-Drake-08-2000x1000.jpg
Your regex does not work as expected primarily because of an unescaped dot in (.\S+)$ part. An unescaped . matches any character but a newline. However, \S matches any non-whitespace, including a .. Besides unnecessary backtracking, you may get an unexpected result with a string like http://az648995.vo.msecnd.net/win/2015/11/slot-Drake-08-2000x1000-1024x512.MORE_TEXT_HERE.jpg.
Assuming the extension is the part of a string after the last dot, you can use
-\d+x\d+(\.[^.\s]+)$
See regex demo
The nagated character class [^.\s] matches any character but whitespace and a literal . symbol. Note that there is no point in using a callback function inside a replace, you can use a mere $1 backreference.
JS demo:
var src = 'http://az648995.vo.msecnd.net/win/2015/11/slot-Drake-08-2000x1000-1024x512.jpg';
src = src.replace(/-\d+x\d+(.[^.\s]+)$/, "$1");
document.body.innerHTML = src;
Try escaping the . and you will be fine:
/-\d+x\d+(\.\S+)$/
Slightly change the regex to be a little more explicit:
/-\d+x\d+(\.[^\s-]+)$/
The regex can be simplified to the following
Replace
-\d+x\d+(\.\S+)
With
$1
var string = input.replace(/\[noparse\]([^\]]+)?\[\/noparse\]/ig, '<noparse>'+removeBrackets('$1')+'</noparse>');
This expression should be taking a string and encoding the parts wrapped in [noparse] tags so they don't render in a textarea.
I tested this as:
var string = input.replace(/\[noparse\]([^\]]+)?\[\/noparse\]/ig, '<noparse>test</noparse>');
and:
var string = input.replace(/\[noparse\]([^\]]+)?\[\/noparse\]/ig, '<noparse>'+String('$1')+'</noparse>');
and they work (without the desired effect).
function removeBrackets(input){
return input
.replace(/\[/g, '[')
.replace(/\]/g, '\');
}
What am I doing wrong in trying to pass the back reference into the removeBrackets function?
replace takes a function as callback and passes the capturing groups in the arguments:
var regex = /\[noparse\]([^\]]+)?\[\/noparse\]/ig;
string = string.replace(regex, function(_, match) {
return '<tag>'+ removeBrackets(match) +'</tag>';
});
The first param _ is the full string, unnecessary in most cases.
Your regular expression won't work, because of an error in the negative character set you're using. This fixes it:
input.replace(/\[noparse\]([^\[]+)?\[\/noparse\]/ig, '<noparse>test</noparse>');
^
Then, to perform the actual replacement, you need to pass a function as the second argument to .replace() instead of a simple string.
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)
I'm trying to make an auto-complete function for twitter usernames.
So far, I have the following code:
function OnKeyUp(txtboxid){
var text = $('#'+txtboxid).val()
var regex = '(^|\s)#(\w*[a-zA-Z_]+\w*)'
var results = text.match(RegExp(regex, 'gm'))
console.debug(results)
}
The problem is, it matches only text when it is at the beginning of the string (eg: #yser)
What i want is a regex that can mach such a string like this "hello #user2 , #user and #user3 how are you"
I'm not sure how to accomplish this.
Searched google for about 3 hours now and still nothing found.
Also, it would be great to only the the last username when its changed.
Your regex is fine. The only problem is that backslashes in the string will be removed or replaced when the string is parsed, instead of being interpreted by the regular expression parser. You need to re-escape each of them with an extra backslash:
var regex = '(^|\\s)#(\\w*[a-zA-Z_]+\\w*)';
Instead of specifying the regular expression with a string and the RegEx function, you should usually use a regular expression literal. It's delimited by backslashes instead of double-quotes, with the flags appended to the end:
var results = text.match(/(^|\s)#(\w*[a-zA-Z_]+\w*)/gm);