Invert brace from { to } and vise versa - javascript

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(",", "}");

Related

Can someone explain me this behaviour?

Why in the first case there're backslashes while in the second one there is? The escape function shouldn't change anything right? And even if it was the most logic would be str.replace('\'', '\\\'') , so... Thanks in advance.
escape = function(str) {
str = str.replace('\\', '\\\\')
str = str.replace('\'', '\\\'')
str = str.replace('\"', '\\\"')
str = str.replace('\0', '')
str = str.replace('\r', '\\r')
str = str.replace('\n', '\\n')
return str;
}
var original = ("Maura';--");
var escaped = escape("Maura';--");
//var encoded = btoa(escaped);
console.log(original);
console.log(escaped);
//console.log(encoded);
Output:
'Maura';--'
'Maura\';--'
In the first case you are not apply the escape function on the string original. In the second case its changed due to second line of the escape function
str = str.replace('\'', '\\\'')
The above line is same as
str = str.replace("'", '\\\'').
And the second part \\\' will become \'.

Check the end of a string for valid regex and return the string trimmed of the regex-

Here is an attempt to explain a bit clearer with code--
str = 'testfoostringfoo';
var regex = /foo$/;
if (str.match(regex) == true) {
str.trim(regex);
return str; //expecting 'testfoostring'
}
I'm looking for the simplest way to accomplish this using only javascript, though jQuery is available. Thanks for your time. :]
Fully functioning code with the help from #Kobi-
var str = 'testfoostringfoo';
var regex = /f00$/;
if (str.match(regex)) {
str = str.replace(regex, '');
return str; //returns 'testfoostring' when the regex exists in str
}
You should simply replace:
str = 'testfoostringfoo';
var regex = /foo$/;
str = str.replace(regex, '');
return str;
I removed the if, replace does not affect the string when regex is not found.
Keep in mind that match returns an array of matches (['foo']), so the comparison to true fails either way: the condition in if(str.match(regex) == true) is always false.
You're looking for if(str.match(regex)) or if(regex.test(str)).
Note that trim is somewhat new in JavaScript, and it doesn't take parameters, it just removes whitespaces.

How to remove the extra spaces in a string?

What function will turn this contains spaces into this contains spaces using javascript?
I've tried the following, using similar SO questions, but could not get this to work.
var string = " this contains spaces ";
newString = string.replace(/\s+/g,''); // "thiscontainsspaces"
newString = string.replace(/ +/g,''); //"thiscontainsspaces"
Is there a simple pure javascript way to accomplish this?
You're close.
Remember that replace replaces the found text with the second argument. So:
newString = string.replace(/\s+/g,''); // "thiscontainsspaces"
Finds any number of sequential spaces and removes them. Try replacing them with a single space instead!
newString = string.replace(/\s+/g,' ').trim();
string.replace(/\s+/g, ' ').trim()
Try this one, this will replace 2 or 2+ white spaces from string.
const string = " this contains spaces ";
string.replace(/\s{2,}/g, ' ').trim()
Output
this contains spaces
I figured out one way, but am curious if there is a better way...
string.replace(/\s+/g,' ').trim()
I got the same problem and I fixed like this
Text = Text.replace(/ {1,}/g," ");
Text = Text.trim();
I think images always explain it's good, basically what you see that the regex \s meaning in regex is whitespace. the + says it's can be multiply times. /g symbol that it's looks globally (replace by default looks for the first occur without the /g added). and the trim will remove the last and first whitespaces if exists.
Finally, To remove extra whitespaces you will need this code:
newString = string.replace(/\s+/g,' ').trim();
We can use the below approach to remove extra space in a sentence/word.
sentence.split(' ').filter(word => word).join(' ')
Raw Javascript Solution:
var str = ' k g alok deshwal';
function removeMoreThanOneSpace() {
String.prototype.removeSpaceByLength=function(index, length) {
console.log("in remove", this.substr(0, index));
return this.substr(0, index) + this.substr(length);
}
for(let i = 0; i < str.length-1; i++) {
if(str[i] === " " && str[i+1] === " ") {
str = str.removeSpaceByLength(i, i+1);
i = i-1;
}
}
return str;
}
console.log(removeMoreThanOneSpace(str));
var s=" i am a student "
var r='';
console.log(s);
var i,j;
j=0;
for(k=0; s[k]!=undefined; k++);// to calculate the length of a string
for(i=0;i<k;i++){
if(s[i]!==' '){
for(;s[i]!==' ';i++){
r+=s[i];
}
r+=' ';
}
}
console.log(r);
// Here my solution
const trimString = value => {
const allStringElementsToArray = value.split('');
// transform "abcd efgh" to ['a', 'b', 'c', 'd',' ','e', 'f','g','h']
const allElementsSanitized = allStringElementsToArray.map(e => e.trim());
// Remove all blank spaces from array
const finalValue = allElementsSanitized.join('');
// Transform the sanitized array ['a','b','c','d','e','f','g','h'] to 'abcdefgh'
return finalValue;
}
I have tried regex to solve this problem :
let temp=text.replace(/\s{2,}/g, ' ').trim()
console.log(temp);
input="Plese complete your work on Time"
output="Please complete your work on Time"
//This code remove extra spaces with out using "string objectives"
s=" This Is Working On Functions "
console.log(s)
final="";
res='';
function result(s) {
for(var i=0;i<s.length;i++)
{
if(!(final==""&&s[i]==" ")&&!(s[i]===" "&& s[i+1] ===" ")){
final+=s[i];
}
}
console.log(final);
}
result(s);

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).

How can I trim the leading and trailing comma in javascript?

I have a string that is like below.
,liger, unicorn, snipe,
how can I trim the leading and trailing comma in javascript?
because I believe everything can be solved with regex:
var str = ",liger, unicorn, snipe,"
var trim = str.replace(/(^,)|(,$)/g, "")
// trim now equals 'liger, unicorn, snipe'
While cobbal's answer is the "best", in my opinion, I want to add one note: Depending on the formatting of your string and purpose of stripping leading and trailing commas, you may also want to watch out for whitespace.
var str = ',liger, unicorn, snipe,';
var trim = str.replace(/(^\s*,)|(,\s*$)/g, '');
Of course, with this application, the value of using regex over basic string methods is more obvious.
If you want to make sure you don't have any trailing commas or whitespace, you might want to use this regex.
var str = ' , , , foo, bar, ';
str = str.replace(/(^[,\s]+)|([,\s]+$)/g, '');
returns
"foo, bar"
Try this, since not everything can be solved by REs and even some things that can, shouldn't be :-)
<script type="text/javascript">
var str = ",liger, unicorn, snipe,";
if (str.substr(0,1) == ",") {
str = str.substring(1);
}
var len = str.length;
if (str.substr(len-1,1) == ",") {
str = str.substring(0,len-1);
}
alert (str);
</script>
In ECMAScript 5 and above, you can now do a one-liner
',liger, unicorn, snipe,'.split(',').map(e => e.trim()).filter(e => e).join(', ')

Categories

Resources