replace function to replace single quote string - javascript

I have this string something='http://example.com/something' and how can I replace the something=' with nothing?
when I do str.replace('something='','') I got syntax error. I tried str.replace('something=\'','') and expect to escape the single quote with slash, it doesn't work too.

str.replace('something='','') will of course lead to a syntax error.
Try
str.replace("something='","")

I believe what you are looking for is a replacement of something=' and all ticks (') including the closing one... So you could use this:
var str = "something='http://example.com/something'";
alert(str.replace(/something='(.*)'/, "$1"));

You need to update the str variable with the returned value since String#replace method doesn't update the variable.
str = str.replace('something=\'', '')
Although it's better to use double quotes instead of escaping.
str = str.replace("something='", '')

Related

How do I remove the string in brackets only from the beginning of the entire string?

I have tried using replace for removing the string in the brackets. But this doesnt work. I want to remove only in the beginning brackets.
var string="(I want to delete this) helloo (not this)";
var replacedString=string.replace(/ *\([^)]*\) */g, "");
You could look for the first bracket at start and for a closing bracket of the string and then replace it.
var string = "(I want to delete this) helloo (not this)",
result = string.replace(/^\([^)]*\)/, '');
console.log(result);
Try below regex, without /g flag
\((.+?)\)
You will get the result in group 1 if you want to preserve brackets,
Regex Demo
This should work in most, if not all, instances:
myString.replace(/\((.*?)\)/, '$1')

How to escape single quote within another string which contains single quote in javascript?

Hi I want to escape single quote within another string.
I have the following string:
'I'm a javascript programmer'
In the above string , I need to escape single quote
and the expected output is:
'I\'m a javascript programmer'
I required this to handle in eval() in javascript.
The String would be like this...
"[['string's one','string two','string's three']]"
How to solve this. Thanks in advance...
This can do the trick:
var str = "'I'm a js programer.'";
str.replace(/(\w)'(\w)/g, "$1\\\'$2");
var s = "my string's"
s = s.replace(/'/g, "\\'");
The proper way to escape quotes in an html string would be with a character entity.
'I'm a javascript programmer'
The same goes for double quotes:
'"I'm a javascript programmer"'
You can try lookahead assertions to achieve the desired effect:
var str = "'I'm a javascript's programmer'";
str = str.replace(/(?!^)'(?!$)/g, "\\'");
(Fiddle). Unlike Shimon's answer, this can also deal with double single quotes ('').
Negative lookahead assertion (?! )doesn't do any matching by itself but it ensures that the asserted expression doesn't occur at the given position (i.e. start of string ^ doesn't occur before the quote and end of string $ doesn't occur after the quote).

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 single quotes in JavaScript string for JavaScript evaluation

I have a project, in which some JavaScript var is evaluated. Because the string needs to be escaped (single quotes only), I have written the exact same code in a test function. I have the following bit of pretty simple JavaScript code:
function testEscape() {
var strResult = "";
var strInputString = "fsdsd'4565sd";
// Here, the string needs to be escaped for single quotes for the eval
// to work as is. The following does NOT work! Help!
strInputString.replace(/'/g, "''");
var strTest = "strResult = '" + strInputString + "';";
eval(strTest);
alert(strResult);
}
And I want to alert it, saying: fsdsd'4565sd.
The thing is that .replace() does not modify the string itself, so you should write something like:
strInputString = strInputString.replace(...
It also seems like you're not doing character escaping correctly. The following worked for me:
strInputString = strInputString.replace(/'/g, "\\'");
Best to use JSON.stringify() to cover all your bases, like backslashes and other special characters. Here's your original function with that in place instead of modifying strInputString:
function testEscape() {
var strResult = "";
var strInputString = "fsdsd'4565sd";
var strTest = "strResult = " + JSON.stringify(strInputString) + ";";
eval(strTest);
alert(strResult);
}
(This way your strInputString could be something like \\\'\"'"''\\abc'\ and it will still work fine.)
Note that it adds its own surrounding double-quotes, so you don't need to include single quotes anymore.
I agree that this var formattedString = string.replace(/'/g, "\\'"); works very well, but since I used this part of code in PHP with the framework Prado (you can register the js script in a PHP class) I needed this sample working inside double quotes.
The solution that worked for me is that you need to put three \ and escape the double quotes.
"var string = \"l'avancement\";
var formattedString = string.replace(/'/g, \"\\\'\");"
I answer that question since I had trouble finding that three \ was the work around.
Only this worked for me:
searchKeyword.replace(/'/g, "\\\'");//searchKeyword contains "d'av"
So, the result variable will contain "d\'av".
I don't know why with the RegEx didn't work, maybe because of the JS framework that I'm using (Backbone.js)
That worked for me.
string address=senderAddress.Replace("'", "\\'");
There are two ways to escaping the single quote in JavaScript.
1- Use double-quote or backticks to enclose the string.
Example: "fsdsd'4565sd" or `fsdsd'4565sd`.
2- Use backslash before any special character, In our case is the single quote
Example:strInputString = strInputString.replace(/ ' /g, " \\' ");
Note: use a double backslash.
Both methods work for me.
var str ="fsdsd'4565sd";
str.replace(/'/g,"'")
This worked for me. Kindly try this
The regular expression in the following code also handles the possibility of escaped single quotes in the string - it will only prepend backslashes to single quotes that are not already escaped:
strInputString = strInputString.replace(/(?<!\\)'/g, "\\'");
Demo: https://regex101.com/r/L1lF7J/1
Compatibility
The regex above uses negative lookbehind, which is widely supported but if using an older Javascript version, this clunkier regex (which uses a capturing group backreference instead) will also do the job:
strInputString = strInputString.replace(/(^|[^\\])'/g, "$1\\'");
Demo: https://regex101.com/r/9niyYw/1
strInputString = strInputString.replace(/'/g, "''");

Javascript Replace text in string

I'm having some troubles getting regex to replace all occurances of a string within a string.
**What to replace:**
href="/newsroom
**Replace with this:**
href="http://intranet/newsroom
This isn't working:
str.replace(/href="/newsroom/g, 'href="http://intranet/newsroom"');
Any ideas?
EDIT
My code:
str = 'photo';
str = str.replace('/href="/newsroom/g', 'href="http://intranet/newsroom"');
document.write(str);
Thanks,
Tegan
Three things:
You need to assign the result back to the variable otherwise the result is simply discarded.
You need to escape the slash in the regular expression.
You don't want the final double-quote in the replacement string.
Try this instead:
str = str.replace(/href="\/newsroom/g, 'href="http://intranet/newsroom')
Result:
photo
You need to escape the forward slash, like so:
str.replace(/href="\/newsroom\/g, 'href=\"http://intranet/newsroom\"');
Note that I also escaped the quotes in your replacement argument.
This should work
str.replace(/href="\/newsroom/g, 'href=\"http://intranet/newsroom\"')
UPDATE:
This will replase only the given string:
str = 'photo';
str = str.replace(/\/newsroom/g, 'http://intranet/newsroom');
document.write(str);

Categories