How can I reverse the order of Duck, Donald with Javascript?
I am currently retrieving Duck, Donald from a query string and I would like to be able to display it on the page, receiving it as Dondald Duck.
I am using document.write("Name: " + Request.QueryString("name")); to write Duck, Donald to the page and I would also like to be able to change 'Mouse', 'Mickey G' to just 'Mickey Mouse'.
var name = Request.QueryString("name").Item(1).split(",").reverse().join(" ").trim();
if(name.split(" ").length > 2) {
name = name.split(" ");
name.splice(1, 1);
name = name.join(" ");
}
document.write(name);
Example at http://jsfiddle.net/6AdGs/
You can split the string using split method, and then past them in correct order:
var str = 'Duck, Donald';
var parts = str.split(',');
document.write(parts[1] + ' ' + parts[0]);
Basically thats what you need to do. Hope it helps!
This function may help you.
<script>
function reverseName(str) {
var tail = str.substr(0, str.indexOf(","));
var head = str.substr(str.indexOf(",") + 1);
return head + ' ' + tail;
}
document.write("Name: " + reverseName(Request.QueryString("name")));
</script>
As above, but consider: Are first names and surnames always separated by commas? It becomes relevant with some non-English names you may find like 'Silva dos Santos, Miguel Jesus', where Silva dos Santos are the family names and Miguel Jesus are given names.
Related
I need a algorithm which is doing something like this:
var example = "Hello $$user$$ your real name is $$realname$$. Have a good day"
Output --> ["Hello ", "$$user$$", " your real name is ", "$$realname$$", ". Have a good day"]
Hence, split the part by a selected character and put them together in a string array. Can someone help me out?
I'm looking for a solution with JavaScript/jQuery
It seems you want to split by pattern $$...$$; You could use /(\$\$.*?\$\$)/; To keep the pattern in the result, you can make it a capture group, and also make it lazy (?) so that it will split with the shortest length pattern matched:
example.split(/(\$\$.*?\$\$)/)
#[ 'Hello ',
# '$$user$$',
# ' your real name is ',
# '$$realname$$',
# '. Have a good day' ]
Yes, this is possible with JavaScript itself... Slightly tricky, but yes.
var strings = [], tokens = [];
var str = "Hello $$user$$ your real name is $$realname$$. Have a good day".replace(/\$\$(.*?)\$\$/g, "\$\$TOKEN$1\$\$").split("$");
for (var i = 0; i < str.length; i++) {
if (str[i].indexOf("TOKEN") === 0) {
// This is a token.
tokens.push(str[i].replace("TOKEN", ""));
} else {
strings.push(str[i]);
}
}
str = str.map(function (v) {
if (v.indexOf("TOKEN") === 0)
return "$$" + v.replace("TOKEN", "") + "$$";
return v;
});
console.log(str);
console.log(strings);
console.log(tokens);
The above code will split everything into tokens. And on top of it, it also separates the strings and tokens out. The above one gives as per your requirement:
[
"Hello ",
"$$user$$",
" your real name is ",
"$$realname$$",
". Have a good day"
]
Kindly note, there's nothing like {value, value}, there's only [value, value].
String.split()
The split() method splits a String object into an array of strings by separating the string into substrings.
var example = "Hello $$user$$ your real name is $$realname$$. Have a good day";
var exSplit = example.split("$$");
var userIdx = exSplit.indexOf("user");
var nameIdx = exSplit.indexOf("realname");
document.querySelector(".user").innerHTML = exSplit[userIdx];
document.querySelector(".name").innerHTML = exSplit[nameIdx];
<div class="user"></div>
<div class="name"></div>
Though, if I may suggest, variables can handle this type of operation without all of the hassle.
Having a list (array) of tags ['tag1', 'tag2', 'tag3'] I want to generate a nice title like: Content tagged tag1, tag2 and tag3.
For the moment I have:
"Content tagged " + tags_titles.join(" and ");
with the result:
Content tagged tag1 and tag2 and tag3
I know it's a simple question, but I am curious if there is a nice solution for this case.
You could get the two last elements and join them with ' and ' and put it as last element back into the array and later join all elements with ', ' for getting a nice string.
Methods
Array#concat, joins two arrays and returns a new array
Array#splice, for getting the last two elemensts of the array
Array#join, joins an array with the given spacer.
This proposal works for any length of an array, even with one or two elements.
function nice([...array]) {
return array.concat(array.splice(-2, 2).join(' and ')).join(', ');
}
console.log("Content tagged " + nice(['tag1']));
console.log("Content tagged " + nice(['tag1', 'tag2']));
console.log("Content tagged " + nice(['tag1', 'tag2', 'tag3']));
A bit of slicing and dicing using Array.prototype.slice:
function naturalLanguageJoin(arr){
if(!arr)
return '';
if(arr.length<2)
return (arr.length>0) ? arr[0] : '';
return arr.slice(0,arr.length-1).join(", ") + " and " + arr[arr.length-1];
}
console.log(naturalLanguageJoin(['tag1', 'tag2', 'tag3']));
console.log(naturalLanguageJoin(['tag1', 'tag2']));
console.log(naturalLanguageJoin(['tag1']));
console.log(naturalLanguageJoin([]));
console.log(naturalLanguageJoin(null));
An array can be treated as a stack so you can pop the last element and in turn write this
var last = tags_titles.pop();
last = tags_titles.length ? ` and ${last}` : last;
`Content tagged ${tags_titles.join(", ")} ${last}`
The code uses ES6 string templates, which I generally find to be more readable than doing string concatenation in the code. It also utilizes the fact that the pop method essentially performs to operations. Gets the lasst element of the array and mutate the array. That eliminate the need to do the mutation explicitly (using slice)
Try like this
var g = ['tag1', 'tag2', 'tag3'];
var title = g.slice(0, g.length-1).join(',').concat(' and ').concat(g[g.length-1]);
From my view, This is an simple approach
var tags = ['tag1', 'tag2', 'tag3'];
console.log("Content tagged " + tags.slice(0, -1).join(', ')+' and '+tags.slice(-1));
Hope it helps you :)
JsFiddle
Try this,
var arr = ['tag1', 'tag2', 'tag3'];
var lastStr = arr.pop();
var str = "Content tagged " + arr.join(", ") + " and " + lastStr;
Something like this would be my approach
function arrayFormat(arr) {
var output = arr.splice(0, arr.length - 1).join(", ");
output += " and " + arr[0];
return output;
}
console.log(arrayFormat(["a", "b", "c"]));
I need your help,
How can the existing code below be modified such that it not only takes into account replacing all the <br>'s with \n's but also all the <nbsp;>'s anywhere in a string with the space separator in javascript?
Here is the existing code that needs to be modified:
var txt = str.replace(/<br\s*\/?>/mg,"\n")
If you want to do it with one regexp, replace accepts a function as the replacer so you could leverage that with a group match:
var str = 'some string <br/> and something else';
var txt = str.replace(/(<br\s*\/?>| )/mg, function (match) {
return match === ' ' ? ' ' : '\n';
});
document.write('<pre>' + txt + '</pre>');
If not, you can also chain together as many replace calls as you want:
var str = 'some string <br/> and something else';
var txt = str.replace(/<br\s*\/?>/gm, '\n').replace(/ /gm, ' ');
document.write('<pre>' + txt + '</pre>');
The main benefit of using one replace is that it won't need to check the entire string twice. However this does make the code a bit harder to read and possibly to maintain if you need to add/edit which entities you want to replace. So depending on the length of the string to be checked you would need to strike a balance between performance and readability/maintainability.
You may use something like this
var txt = str.replace(/<br ?/?>/g, '\n').replace(/ /g, ' ');
but you can't do 2 replacements using 1 regex
I was wondering if there is a safe way (if the data is coming from users) to get the string and the number separated - for example "something-55", "something-124", "something-1291293"
I would want:
something and
55
something and
124
something and
1291293
I mean by a 'safe way' is to be certain I am getting only the number on the end.. if the data is coming from the users "something" could be anything some-thing-55 for example..
I'm looking for a robust way.
try this, working.
var string = 'something-456';
var array = string.split('-');
for (var i = 0;i<array.length;i++){
var number = parseFloat(array[i]);
if(!isNaN(number)){
var myNumber = number;
var mySomething = array[i - 1];
console.log('myNumber= ' + myNumber);
console.log('mySomething= ' + mySomething);
}
}
Can you try this?
var input='whatever-you-want-to-parse-324';
var sections=input.split(/[\w]+-/);
alert(sections[sections.length-1]);
You can use substr along with lastIndexOf:
var str = "something-somethingelse-55",
text = str.substr(0, str.lastIndexOf('-')),
number = str.substr(str.lastIndexOf('-') + 1);
console.log(text + " and " + number);
Fiddle Demo
All though it's a tad late, this would be the most restrictive solution:
var regex = /^([-\w])+?-(\d+)$/,
text = "foo-123",
match = test.match(regex);
You will get a match object back with the following values:
[ "foo-123", "foo", "123" ]
It's a very strict match so that " foo-123" and "foo-123 " would not match, and it requires the string to end in one or more digits.
My input is many lines of text that looks like this:
a.b.c.d.e (f:g)
I need to turn this into
a.b.c.d.e (a/b/c/d/e/f?g)
Note that the dotted part (a.b.c.d.e) can have varying numbers of elements, so sometimes it'll be q.r.s.t, sometimes u.v.w.x.y.z and so on. I have a replace() that will give me (a.b.c.d.e.f?g), but what I need is then to turn all those .s into /s in the result.
Is there a way to do a replace inside a replace? Or should I just call replace() on the string twice?
Sorry if this question is poorly worded, I'm not awfully well versed at regular expressions in javascript.
A very crazy way of doing it:
var str = "a.b.c.d.e (f:g)";
var re = /([^\s]+)\s\(([^:]+):([^\)]+)\)/;
var newStr = str.replace(re, function(a,b,c,d){ return b + " (" + b.replace(/\./g,"/") + "/" + c + "?" + d + ")"; });
jsfiddle
You need to chain the calls to replace() one after the other.
var result = source.replace("foo", "bar").replace("oof", "rab");
A saner way :) http://jsfiddle.net/smfPU/
input = "a.b.c.d.e.w.x.y.z (f:g:h)";
output = input.replace(/:/g, "?");
outputparts = output.split("(");
left = outputparts[0];
middle = left.replace(/\./g, "/").trim();
right = outputparts[1];
output = left + "(" + middle + "/" + right;
document.write(output);