append single quotes to characters - javascript

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

Related

Is there a simple one-liner to split and join a string?

I have a string which looks likes this:
obj.property1.property2
I want the string to become
[obj][property1][property2]
Currently I use a split and later on a for loop to join each other. But I was wondering if there was a more simpler method for doing this, perhaps with using split() and join() toghether. I can't figure out how however.
Currently using:
var string = "obj.property1.property2";
var array = string.split(".");
var output = "";
for(var i = 0;i < array.length;i++) {
output += "[" + array[i] + "]";
};
console.log(output);
Consider using replace with the RegEx global option to replace all instances of '.' with back to back braces, then stick an opening and closing brace on the end like this.
var str ="obj.property1.property2"
console.log("["+str.replace(/\./g,"][")+"]")
'['+string.split('.').join('][')+']'

Problems with first blank value while building a delimiter parser using regex

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.

Separating string with JavaScript

The goal
99999999 to 9999 9999.
The problem
I searched for String.split, but I couldn't apply. I don't want to separate the string into two variables, I just want to separate the string to displaying proposals.
The scenario
There is the following fragment on my application:
var contactPhone = "91929394";
And I want to separate 91929394 into 9192 9394 by calling the same variable (contactPhone).
Clarifying know-how questions
I really don't know the syntax, even not how I have to search for. Take it easy — it is a programming question.
Use contactPhone.replace(/(\d{4})(\d{4})/, '$1 $2')
It will split the phone number into two groups, with 4 digits each.
If contactPhone is a number and not a string, you can use contactPhone.toString() before using the regex replace.
You could simply;
var formatted = contactPhone.toString();
formatted = formatted.substr(0, 4) + " " + formatted.substr(4);
try this:
function sep(str){
var len = str.length;
var a = len/2;
return str.substring(0, a) + ' ' + str.substring(a, len);
}
If you wanted to be more robust, you could add a space after every 4th character?
contactPhone.replace(/.{1,4}/g, '$& ');
Does this help?
function splitInTwo(s){
return [s.substring(0, s.length/2), s.substring(s.length/2)]
}

How can I find a specific string and replace based on character?

I'm trying to find a specific character, for example '?' and then remove all text behind the char until I hit a whitespace.
So that:
var string = '?What is going on here?';
Then the new string would be: 'is going on here';
I have been using this:
var mod_content = content.substring(content.indexOf(' ') + 1);
But this is not valid anymore, since the specific string also can be in the middle of a string also.
I haven't really tried anything but this. I have no idea at all how to do it.
use:
string = string.replace(/\?\S*\s+/g, '');
Update:
If want to remove the last ? too, then use
string = string.replace(/\?\S*\s*/g, '');
var firstBit = str.split("?");
var bityouWant = firstBit.substring(firstBit.indexOf(' ') + 1);

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