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!
Related
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...
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);
I'm building this generic parser that decodes a string to an Array using an specified delimiter.
For this question, I'll use comma as delimiter.
This is my current regex:
var reg = /(\,|\r?\n|\r|^)(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|([^"\,\r\n]*))/gi
It works fine for most cases like:
'a,b,c,d'.match(reg);
returns
["a", ",b", ",c", ",d"] (having the commas with the values is not a problem)
When I have empty values, it also works, for example:
'a,,c,'.match(reg);
returns ["a", ",", ",c", ","] (this is also fine)
The problem is when I have a blank value at the first position:
',b,c,d'.match(reg);
returns [",b", ",c", ",d"] and I was expecting something like: ["", ",b", ",c", ",d"]
Any ideas?
If you want to split by , then the regex is very simple: /,/g.
You can then pass this pattern into the split function.
It will also work with multi-character delimiters e.g. foo.
You can then do something like this:
var pattern = /,/g;
var el = document.getElementById('out');
el.insertAdjacentHTML('beforeend', '<p>Trying with ,</p>');
output('a,b,c,d');
output(',b,c,d');
output(',,,d');
output('a,,c,');
el.insertAdjacentHTML('beforeend', '<p>Trying with foo</p>');
var pattern = /foo/g;
output('afoobfoocfood');
output('foobfoocfood');
output('foofoofood');
output('afoofoocfoo');
function output(input) {
var item = '<p>' + input + ' gives: ';
var arr = input.split(pattern);
item += '<pre>' + JSON.stringify(arr) + '</pre></p>';
el.insertAdjacentHTML('beforeend', item);
}
<div id="out"></div>
How about something simpler like this regex:
[^\,]*\,(?!$)|[^\,]|\,
The regex above will catch anything between , including special characters. You can build on it to make it match specific type of characters.
This is a working js:
var reg = /[^\,]*\,(?!$)|[^\,]|\,/gi;
var s = ',,b,c,d'.match(reg);
document.write(s[0], '<br>' , s[1] , '<br>' , s[2] , '<br>' , s[3], '<br>' , s[4]);
Thanks to everyone who posted an answer but I ended up going with the solution provided here:
Javascript code to parse CSV data
The solution above also had the problem with an empty value at the first position but solving that with JS in the while loop was easier than fixing the RegEx.
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).
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(/.$/, '\'"')