Replacing in Javascript " with ' - javascript

I have a string and it needs to be passed on as a JSON, but then, inside the string, I cannot have " signs, so I was thinking about replacing them with ' signs in my Javascript.
I tried this:
var myString = myString.replace("\"", "\'");
But unfortunately, it only replaced the first occurrence of " in my string. Help?

You should use a regex to solve the problem.
Hope it helps you.
var myString = 'this "is" a test'
myString = myString.replace(/\"/g, "'");
console.log(myString)

use the regular expression, with the flag g to replace
var myString = myString.replace(/\"/g, '\'');

Here split the string with " and join the string with '.
var data = '[{"endDate":"2017-04-22","req":"2017-04-19","nr":2,"type":"CO","startDate":"2017-04-20","Dep":"2017-04-19"},{"endDate":"2017-04-22","req":"2017-04-20","nr":3,"type":"CM","startDate":"2017-04-20","Dep":"2017-04-19"}]';
var result=data.split('"').join("'");
console.log(result);

You can achieve this using the global flag /g. Try this:
var myString=myString.replace(/"/g,"\'");

var s = 'This " is " Just " for test'.replace(/\"/g, "'");
console.log(s);

Related

String replace expressions

I have the following string:
var myString = "Name: ";
function replaceName(str, name) {
return str.replace(/Name:/gi, "Name:" + name);
}
myString = replaceName("Name: ", "Joe");
myString = replaceName("Name: ", "Jane");
I want to replace the entire line each time a new name is added. The above keeps appending the name to the end of the string.
How can I replace the name each time str.replace is called?
Firstly, you could have mentioned clearly that calling the function second time messes up. And secondly, there's no functions in your code, so you need to tell which line is messing up. I understood the question with the help of Rory McCrossan and here's the answer.
I changed the code and using this RegEx worked:
var str = "Name: ";
str = str.replace(/Name:.*/gi, "Name:" + "Joe");
console.log(str);
str = str.replace(/Name:.*/gi, "Name:" + "Prav");
console.log(str);
Explanation for the RegEx
psst: There's no better explanation than RegEx101...

Add to current string using javascript

I would like to add to the current string using javascript. Currently, It is working fine but I am doing it in a very dirty way currently. I am basically replacing the WHOLE string instead of just adding to it. Is there a way that I can just add a comma and continue my string?
JS:
var mystring = "'bootstrap'"
console.log(mystring.replace(/bootstrap/g , "'bootstrap', 'bootstrap2', 'bootstrap3'"));
JSFiddle
You can add to the end of a string by using the +=operator. See the docs regarding string operators.
var mystring = "'bootstrap'"
mystring += ", 'bootstrap2'";
mystring += ", 'bootstrap3'";
console.log(mystring);
You can concatenate( + operator ) instead of replace if you just want the second string to get appended to the first string.
var mystring = "'bootstrap'"
var newString = mystring +", "+ "'bootstrap', 'bootstrap2', 'bootstrap3'";
console.log( newString );
What about:
mystring += "'bootstrap2',";
or
var arr = ["str1", "str2", "str3"];
var mystring = arr.map((e)=>{return "'"+e+"'";}).join(",")
Array.map function used to wrap each string with single quates, than you Array.join - used to put "," between members
You can concat strings with the + operator:
var mystring = "'bootstrap'" + ",";
console.log(mystring);
Use an array and the join method.
var arr = [];
var myString = "bootstrap";
arr.push(myString);
arr.push(myString);
arr.push("other string");
arr.push("bootstrap");
// combine them with a comma or something else
console.log(arr.join(', '));
It is not suggested, but if you want to keep symbols and not care about order, and want to only add to a string beginning with 'bootstrap':
myString = "'bootstrap'";
console.log(myString.replace(/^(?='(bootstrap)')/, "'$12', '$13', "));
or you can just use capture group to keep it short
mystring.replace(/'(bootstrap)'/, "'$1', '$12', '$13'")

Invert brace from { to } and vise versa

I have a string with { and } how can I take all of them and reverse them, so all { become } and } become {?
I can't do this:
str = str.replace("}", "{");
str = str.replace("{", "}");
because that will make A face the same way as B then it will replace B which will all change them to the same direction.
I tried doing this:
str = str.replace(["{", "}"], ["}", "{"]);
But that just doesn't seem to do anything (not even error out).
So, what can I do to invert them?
You could use a regexp with a callback function to solve this:
str.replace(/\{|\}/g, function(match) {
return match == "}" ? "{" : "}";
});
You can use a temporary string that will definitely be unique to do the swap:
str = str.replace("}", "TEMP_HOLDER");
str = str.replace("{", "}");
str = str.replace("TEMP_HOLDER", "{");
But it's prone to a bug if the string contains the temp string and it also doesn't replace more than one occurrence. I'd suggest using Erik's answer.
You need to convert to something else in the first pass, and then convert to what you want after you've made the other conversions.
str = str.replace("{", "_###_");
str = str.replace("}", "{");
str = str.replace("_###_", "}");
Of course, the something else will need to be something that won't otherwise be in your string. You could use "\r\n" if you are sure you string won't contain newlines.
You could go with a two stage solution:
str = str.replace("}", "~");
str = str.replace("{", ",");
str = str.replace("~", "{");
str = str.replace(",", "}");

append single quotes to characters

I have a string like
var test = "1,2,3,4";
I need to append single quotes (' ') to all characters of this string like this:
var NewString = " '1','2','3','4' ";
Please give me any suggestion.
First, I would split the string into an array, which then makes it easier to manipulate into any form you want. Then, you can glue it back together again with whatever glue you want (in this case ','). The only remaining thing to do is ensure that it starts and ends correctly (in this case with an ').
var test = "1,2,3,4";
var formatted = "'" + test.split(',').join("','") + "'"
var newString = test.replace(/(\d)/g, "'$1'");
JS Fiddle demo (please open your JavaScript/developer console to see the output).
For multiple-digits:
var newString = test.replace(/(\d+)/g, "'$1'");
JS Fiddle demo.
References:
Regular expressions (at the Mozilla Developer Network).
Even simpler
test = test.replace(/\b/g, "'");
A short and specific solution:
"1,2,3,4".replace(/(\d+)/g, "'$1'")
A more complete solution which quotes any element and also handles space around the separator:
"1,2,3,4".split(/\s*,\s*/).map(function (x) { return "'" + x + "'"; }).join(",")
Using regex:
var NewString = test.replace(/(\d+)/g, "'$1'");
A string is actually like an array, so you can do something like this:
var test = "1,2,3,4";
var testOut = "";
for(var i; i<test.length; i++){
testOut += "'" + test[i] + "'";
}
That's of course answering your question quite literally by appending to each and every character (including any commas etc.).
If you needed to keep the commas, just use test.split(',') beforehand and add it after.
(Further explanation upon request if that's not clear).

Put quotes around a variable string in JavaScript

I have a JavaScript variable:
var text = "http://example.com"
Text can be multiple links. How can I put '' around the variable string?
I want the strings to, for example, look like this:
"'http://example.com'"
var text = "\"http://example.com\"";
Whatever your text, to wrap it with ", you need to put them and escape inner ones with \. Above will result in:
"http://example.com"
var text = "http://example.com";
text = "'"+text+"'";
Would attach the single quotes (') to the front and the back of the string.
I think, the best and easy way for you, to put value inside quotes is:
JSON.stringify(variable or value)
You can add these single quotes with template literals:
var text = "http://example.com"
var quoteText = `'${text}'`
console.log(quoteText)
Docs are here. Browsers that support template literals listed here.
Try:
var text = "'" + "http://example.com" + "'";
To represent the text below in JavaScript:
"'http://example.com'"
Use:
"\"'http://example.com'\""
Or:
'"\'http://example.com\'"'
Note that: We always need to escape the quote that we are surrounding the string with using \
JS Fiddle: http://jsfiddle.net/efcwG/
General Pointers:
You can use quotes inside a string, as long as they don't match the
quotes surrounding the string:
Example
var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
Or you can put quotes inside a string by using the \ escape
character:
Example
var answer='It\'s alright';
var answer="He is called \"Johnny\"";
Or you can use a combination of both as shown on top.
http://www.w3schools.com/js/js_obj_string.asp
let's think urls = "http://example1.com http://example2.com"
function somefunction(urls){
var urlarray = urls.split(" ");
var text = "\"'" + urlarray[0] + "'\"";
}
output will be text = "'http://example1.com'"
In case of array like
result = [ '2015', '2014', '2013', '2011' ],
it gets tricky if you are using escape sequence like:
result = [ \'2015\', \'2014\', \'2013\', \'2011\' ].
Instead, good way to do it is to wrap the array with single quotes as follows:
result = "'"+result+"'";
You can escape " with \
var text="\"word\"";
http://jsfiddle.net/beKpE/
Lets assume you have a bunch of urls separated by spaces. In this case, you could do this:
function quote(text) {
var urls = text.split(/ /)
for (var i = 0; i < urls.length; i++) urls[i] = "'" + urls[i] + "'"
return urls.join(" ")
}
This function takes a string like "http://example.com http://blarg.test" and returns a string like "'http://example.com' 'http://blarg.test'".
It works very simply: it takes your string of urls, splits it by spaces, surrounds each resulting url with quotes and finally combines all of them back with spaces.
var text = "\"http://www.example1.com\"; \"http://www.example2.com\"";
Using escape sequence of " (quote), you can achieve this
You can place singe quote (') inside double quotes without any issues
Like this
var text = "'http://www.ex.com';'http://www.ex2.com'"
Another easy way to wrap a string is to extend the Javascript String prototype:
String.prototype.quote = function() { return "\"" + this + "\""; };
Use it like this:
var s = "abc";
console.log( "unwrapped: " + s + ", wrapped: " + s.quote() );
and you will see:
unwrapped: abc, wrapped: "abc"
This can be one of several solutions:
var text = "http://example.com";
JSON.stringify(text).replace('\"', '\"\'').replace(/.$/, '\'"')

Categories

Resources