Javascript add string to start - javascript

my code:
var test = "aa";
test += "ee";
alert(test);
Prints out "aaee"
How can I do the same thing, but add the string not to end, but start:
Like this:
var test = "aa";
test = "ee" + test;
This is the long way, but is there somekind of shorter way like in 1st example?
What I want is that I must not write the initial variable out again in definition.

There's no built-in operator that allows you to achieve this as in the first example. Also test = "ee" + test; seems pretty self explanatory.

You could do it this way ..
test = test.replace (/^/,'ee');
disclaimer: http://xkcd.com/208/

You have a few possibilities although not a really short one:
var test = "aa";
// all yield eeaa
result = "ee" + test;
result = test.replace(/^/, "ee");

var test = "aa";
alert('ee'.concat(test));

What you have, test = "ee" + test; seems completely fine, and there's no shorter way to do this.
If you want a js solution on this you can do something like,
test = test.replace(/^/, "ee");
There are a whole lot of ways you can achieve this, but test = "ee" + test; seems the best imo.

You can add a string at the start (multiple times, if needed) until the resulting string reaches the length you want with String.prototype.padStart(). like this:
var test = "aa";
test = test.padStart(4, "e");
alert(test);
Prints out
eeaa
var test = "aa";
test = test.padStart(5, "e");
alert(test);
Prints out
eeeaa

Related

Regex append characters to a substring

My string comes in two flavours-
var a = /aid/f82eb514073124cd10d468b74eee5663?sg=1#/propertyinfo
or
var a = /aid/f82eb514073124cd10d468b74eee5663#/propertyinfo
I want to append the content that comes after aid/ and before ? or # with "-test". In either of the above scenarios the result would be f82eb514073124cd10d468b74eee5663-test
hence
a = /aid/f82eb514073124cd10d468b74eee5663-test#/propertyinfo
or
a = = /aid/f82eb514073124cd10d468b74eee5663-test?sg=1#/propertyinfo
Seems like you're looking for something like this.
Regular expression /\/aid\/[0-9A-F]*/i and replacement expression $0-test.
JavaScript is a little bit different than just plain regular expression antics, so here you go;
var a = "/aid/f82eb514073124cd10d468b74eee5663?sg=1#/propertyinfo";
alert(a.replace(/(\/aid\/[0-9A-F]*)/i, "$1-test"));
given your examples I guess that string after /aid/ is some kind of md5 hash
this should work for you:
'/aid/f82eb514073124cd10d468b74eee5663#/propertyinfo'.replace(new RegExp('/aid/([a-f0-9]{32})'), '$1-test');
if you don't want to be that much specific about length, you can try the following:
'/aid/f82eb514073124cd10d468b74eee5663#/propertyinfo'.replace(new RegExp('/aid/([a-f0-9]+)'), '$1-test');
Simple solution using String.replace function:
var a = '/aid/f82eb514073124cd10d468b74eee5663sg=1#/propertyinfo',
result = a.replace(/aid\/([^?#]+)(?=\?|#)/, "aid/$1-test");
console.log(result); // /aid/f82eb514073124cd10d468b74eee5663-test?sg=1#/propertyinfo
I suggest replacing directly the # or ? so the regex is nice and simple. :)
var a = "/aid/f82eb514073124cd10d468b74eee5663?sg=1#/propertyinfo";
var b = "/aid/f82eb514073124cd10d468b74eee5663#/propertyinfo";
console.log(a.replace(/([\?#])/,"-test$1"));
console.log(b.replace(/([\?#])/,"-test$1"));
var a = '/aid/f82eb514073124cd10d468b74eee5663?sg=1#/propertyinfo';
a.replace(/(\/aid\/.+)(\?sg=1)(#\/propertyinfo)/,function(text,c,d,e){
return c+'-test'+e;
})
//Output: "/aid/f82eb514073124cd10d468b74eee5663-test#/propertyinfo"
a.replace(/(\/aid\/.+)(\?sg=1#\/propertyinfo)/,function(text,c,d){
return c+'-test'+d;
});
//Output: "/aid/f82eb514073124cd10d468b74eee5663-test?sg=1#/propertyinfo"

Split multiple words started with # sign

var test = "Hello all, this is a message and i want to mention #john, #smith and #jane...";
And what i want to get is:
var result = ["john", "smith", "jane"];
i can take the last username in the string but not all of them. I am OK with regexp or other string functions.
Thank you.
It seems that it's not possible using a single regex :
var result = test.match(/#\w+/g).join('').match(/\w+/g);
You might need to deal with situations in which the regex finds nothing :
var result = test.match(/#\w+/g);
result = result ? result.join('').match(/\w+/g) : [];
var test = "Hello all, this is a message and i want to mention #john, #smith and #jane...";
var patt = /(^|\s)#([^ ]*)/g;
var answer = test.match(patt)
Should get what you want
Like this JSfiddle
Try this regex
/(^|\W)#\w+/g
JavaScript:
var test = "Hello all, this is a message and i want to mention #john, #smith and #jane";
var names = test.match(/(^|\W)#\w+/g);
console.log(names);
Result:
0: "#john"
1: "#smith"
2: "#jane"
Live example on RegExr:
http://regexr.com?36t6g

regex to find a string that comes after =

I´m really new to regex and I have been looking around to find an answer but either it dont work or I get some kind of error so I will try to ask the question and hopefulyl somebody can guide me through it :)
I have a string that can look like this:
str = "car[brand=saab][wheels=4]"
I have no idea if you can get several different matches directly or if you need different .match() but anyhow.
I need everything before the first [] in 1 variable.
Then i need saab in another, and 4 in a third.
.replace with a callback function is your tool of choice when parsing custom formats in javascript. Consider:
parse = function(s) {
var result = {};
s.replace(/^(\w+)|\[(.+?)=(.+?)\]/g, function($0, $1, $2, $3) {
result[$2 || "kind"] = $1 || $3;
});
return result;
}
Example:
str = "car[brand=saab][wheels=4][price=1234][morestuff=foobar]"
console.log(parse(str))
// {"kind":"car","brand":"saab","wheels":"4","price":"1234","morestuff":"foobar"}
You can use this regex:
([^\[]*)\[[^=]+=([^\]]*)\]\[[^=]+=([^\]]*)\]
You can then grap matching group #1, #2 and #3
Live Demo: http://www.rubular.com/r/XNZfHcMAp8
In Javascript:
str = 'car[brand=saab][wheels=4]';
console.log('match::' + str.match(/([^[]*)\[[^=]+=([^\]]*)\]\[[^=]+=([^\]]*)\]/));
I think this should work :
([^[]+)(?:\[[^=]+=([^\]]+)\])+
Explainations :
([^[]) First, you match everything that is not a [.
(?:...)+ Then, when you find it, you're starting repeting a pattern
\[[^=] Find everything that is not an =, and discard it.
([^\]]) Find everything that is not a ] and capture it.
/([^\[]+)\[brand=([^\]]+)\]\[wheels=(\d)\]/
Works.
Try it like
var result = "car[brand=saab][wheels=4]".match(/([^\[]+)\[brand=([^\]]+)\]\[wheels=(\d)\]/)
Result would be
[ "car[brand=saab][wheels=4]", "car", "saab", "4" ]
you could do it with match in one shot, and get an array back.
below lines were tested in chrome console:
str = "car[brand=saab][wheels=4]";
"car[brand=saab][wheels=4]"
str.match(/[^=[\]]+(?=[[\]])/g)
["car", "saab", "4"]
function getObject(str) {
var props = str.split(/\[(.*?)\]/g),
object = {};
if (props.length) {
object.name = props.shift();
while (props.length) {
var prop = props.shift().split("=");
if(prop.length == 2){
object[prop[0]] = prop[1];
}
}
}
return object;
}
console.log(getObject("car[brand=saab][wheels=4]"));

Using Regex Subpatterns in Object Keys (using .replace())

I have a question about the way .replace() works
I know that we can use subpatterns within the replace text like this
var somestr="foobar";
var newstr = somestr.replace(/foo([a-zA-Z]*)/g,"bar$1")
alert(newstr) //"barbar"
However, I am wondering if it is even possible to use the subpattern in an object property, like this.
var somestr = "foobar";
var someobj = {bar:'fuu',two:'uuf'}
var newstr = somestr.replace(/foo([a-zA-Z]*)/g, someobj["$1"])
alert(newstr) //"fuu" ?
My expected result would have been to get the 'bar' property of someobj, which would be "fuu", however the actual result is undefined, which would lead me to believe this is impossible.
How could I otherwise accomplish similar functionality?
Perhaps one of you JS gurus could shed some light on this.
The real-world purpose behind this is I have a template system that uses shorttags to display pieces of data from a requested JSON object, who's code I am attempting to streamline.
Not like this, I added $1 to show the fail:
var somestr = "foobar";
var someobj = {bar:'fuu',two:'uuf', $1: 'test'}
var newstr = somestr.replace(/foo([a-zA-Z]*)/g, someobj["$1"])
newstr; // "test";
but this would work:
var somestr = "foobar";
var someobj = {bar:'fuu',two:'uuf', $1: 'test'}
var newstr = somestr.replace(/foo([a-zA-Z]*)/g, "$1")
someobj[newstr]; // fuu
or maybe better yet, replace takes a function:
var somestr = "foobar";
var someobj = {bar:'fuu',two:'uuf', $1: 'test'}
var newstr = somestr.replace(/foo([a-zA-Z]*)/g, function () {
return someobj[arguments[1]];
})
newstr; // fuu
You can do this:
var someString = "foobar";
var someObject= {bar:'fuu',two:'uuf'};
var re = /foo([a-zA-Z]*)/g;
if (re.test(someString)) {
alert(someObject[RegExp.$1]);
}
See the fiddle here, http://jsfiddle.net/nickyt/AjjjP
You could also just do this alert(someObject[someString.replace(/foo([a-zA-Z]*)/g, "$1")]); but the problem with this is, if nothing is found in $1, your object looks for am empty string key. I would stick with what I have above.

Javascript string separated by a comma

I'm trying to get everything before/after a comma from a string
var test = 'hello,world';
Result:
var one = 'hello';
var two = 'world';
What would be a good way to this?
Thanks
.split
Extra text because I need to write 15 characters for this submission to be approved.
-- edit
okay, more explicitly:
var k = "a,b".split(",");
alert(k[0]);
alert(k[1]);
var test = 'hello,world',
words = test.split(',');
var one = words[0]; // hello
var two = words[1]; // world

Categories

Resources