Match double quotes that doesn't have a preceding escape character - javascript

I have a string that has some double quotes escaped and some not escaped.
Like this,
var a = "abcd\\\"\""
a = a.replace(/\[^\\\]\"/g, 'bcde')
console.log(a)
The string translates to literal, abcd\"".
Now, i am using the above regex to replace non-escaped double quotes.
And only the second double quote must be replaced.
The result must look like this,
abcd\"bcde
But it is returing the same original string, abcd\"" with no replacement.

You can use capture group here:
a = a.replace(/(^|[^\\])"/g, '$1bcde')
//=> abcd\"bcde

A negative lookbehind is what you want. However it is not supported in the Regex' JS flavor.
You can achieve this by processing the result in two steps:
var a = "abcd\\\"\"";
console.log(a);
var result = a.replace(/(\\)?"/g, function($0,$1){ return $1?$0:'{REMOVED}';});
console.log(result);

Related

Javascript replace on multiple Japanese character

I want to replace this
"】|"
character from string with this"】".
mystring is ="【権利確定月】|1月"
and desired output is
"【権利確定月】1月".
I have tried with array operation and also with this code:
mystring.replace(/】|/g, '】')
but not working.
I only want to this with sequence for"】|".
Because after that string will grow like this
example:
"【権利確定月】1月|other|other|【other】other|other|other".
I have tried many other solution provided on stack overflow but all regex contain single character I want for above sequence character.
You need to escape the | because it has a special meaning within regex. 】| equates to 】 or (an empty string) so the result is that it replaces 】 with itself and inserts 】 between all the other characters in the string.
var mystring ="【権利確定月】|1月"
var myModifiedString = mystring.replace(/】\|/g, '】');
console.log(myModifiedString);
You need to escape the logical OR operator as it is a metacharacter in RegEx.
var x = "【権利確定月】|1月".replace(/】\|/g, '】');
console.log(x);
You can define the strings that need to be replaced in separate variables. Following worked for me.
var x = "】|";
var y = "】";
var word = "【権利確定月】|1月";
word.replace(x, y)
You can split your string by 】| and join by 】. Or (as was answered before me) escape | in regex.
const string = '【権利確】|】|定月】|1月';
let splitAndJoin = string.split('】|').join('】');
let replaceRegex = string.replace(/】\|/g, '】');
console.log(splitAndJoin);
console.log(replaceRegex);

splitting of strings in javascript which involves backslash

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"]

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)

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