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

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('][')+']'

Related

how can i replace first two characters of a string in javascript?

lets suppose i have string
var string = "$-20455.00"
I am trying to swap first two characters of a string. I was thinking to split it and make an array and then replacing it, but is there any other way? Also, I am not clear how can I achieve it using arrays? if I have to use arrays.
var string = "-$20455.00"
How can I achieve this?
You can use the replace function in Javascript.
var string = "$-20455.00"
string = string.replace(/^.{2}/g, 'rr');
Here is jsfiddle: https://jsfiddle.net/aoytdh7m/33/
You dont have to use arrays. Just do this
string[1] + string[0] + string.slice(2)
You can split to an array, and then reverse the first two characters and join the pieces together again
var string = "$-20455.00";
var arr = string.split('');
var result = arr.slice(0,2).reverse().concat(arr.slice(2)).join('');
document.body.innerHTML = result;
try using the "slice" method and string concatenation:
stringpart1 = '' //fill in whatever you want to replace the first two characters of the first string with here
string2 = stringpart1 + string.slice(1)
edit: I now see what you meant by "swap". I thought you meant "swap in something else". Vlad's answer is best to just switch the first and the second character.
Note that string[0] refers to the first character in the string, and string[1] to the second character, and so on, because code starts counting at 0.
var string = "$-20455.00";
// Reverse first two characters
var reverse = string.slice(0,2).split('').reverse().join('');
// Concat again with renaming string
var result= reverse.concat(string.slice(2));
document.body.innerHTML = result;
let finalStr = string[1] + string[0] + string.slice(2); //this will give you the result

loop through and .replace using regex

I have a list of url extensions that i want to string replace using regex so that both upper and lower case is captured like this:
str = str.replace(/\.net/i,"")
.replace(/\.com/i,"")
.replace(/\.org/i,"")
.replace(/\.net/i,"")
.replace(/\.int/i,"")
.replace(/\.edu/i,"")
.replace(/\.gov/i,"")
.replace(/\.mil/i,"")
.replace(/\.arpa/i,"")
.replace(/\.ac/i,"")
.replace(/\.ad/i,"")
.replace(/\.ae/i,"")
.replace(/\.af/i,"");
When i try to clean this up using arrays and loops like so, i get an error. Can anyone help me with syntax please
var arr = [ "net","com","org","net","int","edu","gov","mil","arpa","ac","ad","ae"];
str = str.replace(/\.com/i,"")
for(ii==0;ii<=arr.length;ii++){
.replace('/\.'+arr[ii]+'/i',"") // i know this '/\.' and '/i' should not be a string but how would i write it?
}
.replace(/\.af/i,"");
You can just do like this instead of running replace multiple times in a loop:
str = str.replace(/\.(com|net|org|gov|edu|ad|ae|ac|int)/gi, '');
You need to create a RegExp object. You also need to apply .replace to the string, and assign the result.
for (ii = 0; ii < arr.length; ii++) {
str = str.replace(new Regexp('\\.' + arr[ii], 'i'));
}

split equation string by multiple delimiters in javascript and keep delimiters then put string back together

I have an equation I want to split by using operators +, -, /, * as the delimiters. Then I want to change one item and put the equation back together. For example an equation could be
s="5*3+8-somevariablename/6";
I was thinking I could use regular expressions to break the equation apart.
re=/[\+|\-|\/|\*]/g
var elements=s.split(re);
Then I would change an element and put it back together. But I have no way to put it back together unless I can somehow keep track of each delimiter and when it was used. Is there another regexp tool for something like this?
Expanding on nnnnn's post, this should work:
var s = '5*3+8-somevariablename/6';
var regex = /([\+\-\*\/])/;
var a = s.split(regex);
// iterate by twos (each other index)
for (var i = 0; i < a.length; i += 2) {
// modify a[i] here
a[i] += 'hi';
}
s = a.join(''); // put back together
You can also generate regexp dynamically,
var s = '5*3+8-somevariablename/6';
var splitter = ['*','+','-','\\/'];
var splitted = s.split(new RegExp('('+splitter.join('|')+')'),'g'));
var joinAgain = a.join('');
Here splitted array holds all delimiters because of () given in RegExp

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