Replace all in javascript for one occurance - javascript

I have to replace "" (two quotes) with " (one quotes). I used:
string.replace(/""/g,'"')
but if it is having """" (four quotes) it is replacing with " (one quote) it is again replacing the "" (two quotes) with " (one quote).
I need """" (four quotes) should be replaced with "" (two quotes)

The code you provided in your question already does exactly what you say you want it to do:
'I like """"orange"""" and ""apple""'.replace(/""/g,'"');
// Returns:
'I like ""orange"" and "apple"'
'""'.replace(/""/g,'"');
// Returns:
'"'
'""""'.replace(/""/g,'"');
// Returns:
'""'
Unless you're missing some information in your question, there is nothing to solve.
for this reason, I believe the problem is somewhere else in your code.

If you want to replace four quotes with two quotes, this does it:
var string = "\"\"\"\"";
string = string.replace("\"\"\"\"", "\"\"")

Related

How do I properly escape and unescape a multiline string that contains newline literals?

I'm working on a Visual Studio Code extension. The extension is supposed to act on the text that is currently selected in the editor window and send it to an external command (lein-cljfmt in my case, but I think that's unrelated to my question). When the external command is done processing the text I want to replace the current editor selector with the result returned from the command line tool.
Before sending the string I escape it like this:
contents
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\n/g, '\\n');
The result in being unescaped like:
contents
.replace(/\\n/g, '\n')
.replace(/\\"/g, '"')
.replace(/\\\\/g, '\\');
This works in all but one case: when the selection that is being processed contains a string literal that contains a newline literal, the unescaping will instead turn this into a linebreak, thus breaking the code in the editor.
This is an example of a snippet that breaks my escaping:
(defn join
[a b]
(str a "\n" b))
I tried quite some regexp black magic like
.replace(/(?!\B"[^"]*)\\n(?![^"]*"\B)/g, '\n')
by now, but couldn't find a solution that does not have edge cases. Is there a way to do this that I am missing? I also wonder if there is a VSCode extension API that could handle that as it seems to be a common scenario to me.
I think this might be what you need:
function slashEscape(contents) {
return contents
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\n/g, '\\n');
}
var replacements = {'\\\\': '\\', '\\n': '\n', '\\"': '"'};
function slashUnescape(contents) {
return contents.replace(/\\(\\|n|")/g, function(replace) {
return replacements[replace];
});
}
var tests = [
'\\', '\\\\', '\n', '\\n', '\\\n', '\\\\n',
'\\\\\n', '\\\\\\n', '\\"\\\\n', '\n\n',
'\n\n\n', '\\n\n', '\n\\n', '\\n\\n',
'\\\n\\n\nn\n\\n\\\n\\\\n', '"', '\\"', '\\\\"'
];
tests.forEach(function(str) {
var out = slashUnescape(slashEscape(str));
// assert that what goes in is what comes out
console.log(str === out, '[' + str + ']', '[' + out + ']');
});
Trying to unescape the string in 3 stages is really tricky because \n has a different meaning depending on how many slashes there are just before it. In your example the original string of \n (slash n) gets encoded as \\n (slash slash n), then when you decode it the last two characters match the first of your RegExps when what you want is for the first two characters to match the third RegExp. You've got to count the slashes to be sure. Doing it all in one go dodges that problem by decoding those leading slashes at the same time.

Print string literally in javascript

I was trying to write a function convertStr with JavaScript that will print strings literally when used with console.log(convertStr(str)).
Some examples for input and output
str = '\'"\n\\'
console.log(convertStr(str))
> '\'"\n\\'
For doing this convertStr should convert '\'"\n\\' to '\'\\\'"\\n\\\\\''.
Let us consider a simpler example
str = '\''
convertStr(str) =====> '\'\\\'\''
console.log(convertStr(str)) =====> '\''
The first challenge here is to know whether we are enclosing str with ' or ". I don't think this is possible without making assumption.
Let's assume that str is enclosed using '.
The other challenge is there are lot of cases to handle.
After searching the web I tried few solutions
Attempt 1:
I tried JSON.stringify which breaks when I use escaped string quotes inside str
console.log(JSON.stringify('\"')) =====> "\""
console.log(JSON.stringify('\'')) =====> "'"
This solution fails for case with single quotes. This also fails when we use unicode escape
console.log(JSON.stringify('\u2260') ====> "≠"
Attempt 2:
I tried using str.replace(regex, replacestr) but could not find a solution that works for all cases like unicode or things like \x41 or \0.

Wrap a given input string in double quotes if not already wrapped

Background
I need to wrap a JavaScript string in double quotes BUT only if the input string is not already wrapped in double quotes. For this question's purposes "wrapped" is considered as beginning and ending in a double quote regardless of grammar rules.
The Question
What's the best way (regex?) to wrap any input string (empty string included) in double quotes while avoiding duplicate wrapping? Solution should handle internal quotes assuming they are already escaped.
Example inputs/results:
Input:
Hello world
Result:
"Hello world"
Input:
"Hello world"
Result:
"Hello world"
Input:
A quick example says \"hello world\"
Result:
"A quick example says \"hello world\""
Input:
*empty string*
Result:
""
Input:
"Hi," he said, "How are you?"
Result: (considered "wrapped"):
"Hi," he said, "How are you?"
A short and simple way is just to test the first and last characters:
var input = // whatever
var wrapped = input;
if ('"' === wrapped || !('"' === wrapped[0] && '"' === wrapped.slice(-1)))
wrapped = '"' + wrapped + '"';
(This works even on empty strings, because ''[0] is undefined and ''.slice(-1) is '', neither of which cause a problem in the if condition.)
You don't say what to do if the input is just a single double-quote character, but I've assumed for the input '"' the output will be '"""'. If that's not what you want obviously you can modify the code above.
I would avoid using a regex. I'll assume from your examples and comments that the following preconditions hold:
internal quotes, if present, are already escaped
the string is either properly wrapped in (unescaped) double quotes or there are no unescaped double quotes (that is, there is never an unescaped double quote at one end and not the other)
If those assumptions are valid, the problem is much simpler. Just test whether the string starts with a double quote (which perforce wouldn't be escaped, since it's the first character) and whether it ends with an unescaped double quote. If only one is missing, you have a string that doesn't conform to the input assumptions. If both are missing, wrap the string; if neither is missing, the string is already wrapped.
Besides checking for an empty string, you also have to check for a string that consists entirely of one double quote.
You guessed it right. The best bay would be to use regex to wrap your string around quotes. Something like below:-
function quoteMe() {
var inpStr = document.getElementById("input");
inpStr.value = '"' + inpStr.value.replace(/"/g, '') + '"'
document.getElementById("result").innerHTML = inpStr.value;
}
<input type="text" value="" id="input" />
<input type="button" value="Quote Me!" onclick="javascript:quoteMe();">
<div id="result">
</div>
;
I would first take the string and replace double quotes then just add.
var res = str.replace('"', '');
res = '"' + res + '"'

Regular expression for removing whitespaces

I have some text which looks like this -
" tushar is a good boy "
Using javascript I want to remove all the extra white spaces in a string.
The resultant string should have no multiple white spaces instead have only one. Moreover the starting and the end should not have any white spaces at all. So my final output should look like this -
"tushar is a good boy"
I am using the following code at the moment-
str.replace(/(\s\s\s*)/g, ' ')
This obviously fails because it doesn't take care of the white spaces in the beginning and end of the string.
This can be done in a single String#replace call:
var repl = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
// gives: "tushar is a good boy"
This works nicely:
function normalizeWS(s) {
s = s.match(/\S+/g);
return s ? s.join(' ') : '';
}
trims leading whitespace
trims trailing whitespace
normalizes tabs, newlines, and multiple spaces to a single regular space
Try this:
str.replace(/\s+/g, ' ').trim()
If you don't have trim add this.
Trim string in JavaScript?
Since everyone is complaining about .trim(), you can use the following:
str.replace(/\s+/g,' ' ).replace(/^\s/,'').replace(/\s$/,'');
JSFiddle
This regex may be useful to remove the whitespaces
/^\s+|\s+$/g
Try:
str.replace(/^\s+|\s+$/, '')
.replace(/\s+/, ' ');
try
var str = " tushar is a good boy ";
str = str.replace(/^\s+|\s+$/g,'').replace(/(\s\s\s*)/g, ' ');
first replace is delete leading and trailing spaces of a string.

JavaScript Replace - u0009 .... with .replace(/\u0009/g,'');

I'd like to use Javascript to replace all instances of \u009 in a string
This doesn't seem to be working: .replace(/\u0009/g,'');
Do I need to escape something?
First, the question says "replace all instances of \u009 in a string".
But, the regex has replace(/\u0009/g,''); Is this a typo (different number of zeroes)?
Anyway, if the string only contains, unicode, horizontal tab characters (just one char), then the regex is fine.
If it actually contains 6 ascii chars, then the regex needs to be escaped, like so:
var oneChar = 'Pre \u0009 post';
var sixChars = 'Pre \\u0009 post';
//-- NOTE: If not using Firebug, replace 'console.log()' with 'alert()'.
console.log (oneChar + ' becomes --> ' + oneChar.replace (/\u0009/g, "") );
console.log (sixChars + ' becomes --> ' + sixChars.replace (/\\u0009/g, "") );
You need another escape .replace(/\\u009/g,''); :)

Categories

Resources