String replace expressions - javascript

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

Related

Replacing in Javascript " with '

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

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'")

How do I get value from ACE editor without comments?

Is it possible to get the value of an ace editor instance without the comments (single & multi row)? The comments are identified by the span class 'ace_comment', but the only function I found to extract the data is getValue().
Easy Example:
console.log("Hello World") //This is a comment.
What I get:
Output: 'console.log("Hello World") //This is a comment.'
What I want:
Output: 'console.log("Hello World")'
Extended Example (Multi-row + '//' and '/* */' comments):
*/ This is
a comment */ console.log("this is not a comment") // comment again
You can use regular expressions to remove comments:
var string = 'console.log("Hello World") //This is a comment. \n' +
'hello("foo"); /* This is also a comment. */';
string = string.replace(/\s*\/\/.*\n/g, '\n').replace(/\s*\/\*[\s\S]*?\*\//g, '');
document.body.innerHTML = '<pre>' + string + '</pre>';
A simpler solution will be. To just trim the //Comment like this
var str = 'console.log("HelloWorld")//This is a comment';
str = str.split('//');
//Just to print out
document.body.innerHTML = '<pre>You provide > '+ str[0]+'//'+str[1] +'</pre><pre>Output > ' + str[0] + '</pre>';
By doing this you're spliting the the entire string by the '//' split returns an array that will have [0] = console.log('HelloWorld'); and the [1] = 'Comment like this'. This is the simplest solution i can think of. jcubic. Is basically doing the same by using a regex. Good look!

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

Categories

Resources