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

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.

Related

How to use a variable in a match method with regular expression pattern

I want to get an array in JavaScript from a string, cutting it in half.
Example:
// From this:
var myStr = 'cocacola';
// To this:
var myArray = ['coca', 'cola'];
I tried the following method:
var myStr = 'cocacola';
var strHalf = myStr.length / 2;
// This won't work
var myArray = myStr.match(/.{1,strHalf}/g);
// Only this will work fine
var myArray = myStr.match(/.{1,4}/g);
You can do String.slice() to solve this
var myStr = 'cocacola';
let len = myStr.length;
let result = [myStr.slice(0, len/2), myStr.slice(len/2)]
console.log(result);
You'll need to to use the RegExp() constructor and make a string that it understands:
var regexString = "/.{1," + strHalf + "}/g";
var myRegex = new RegExp( regexString );
var myArray = myStr.match( myRegex );
...but be careful doing this; if strHalf is a string containing special characters like / then your RegExp will have weird behaviour.
You can create a non-hardcoded regexp by using the RegExp constructor:
var myArray = myStr.match(new RegExp('/.{1,'+strHalf+'}/g'));
The constructor has no clue that strHalf should be an integer, so make sure you can control that.
This is known to introduce a lot of security issues, please don't use this in production. Regexes are too often used when they shouldn't. If you ever use a regex, do look into other options
There are much better alternatives, but at least it's possible!
You dont need regex for that.
The easiest way is that:
var myStr = 'cocacola';
var strHalf = myStr.length / 2;
var array = [myStr.substr(0, strHalf),myStr.substr(strHalf, myStr.length)];
jsfiddle: https://jsfiddle.net/cudg8qc3/
You can just slice the string and place the first element in the first slot, and the second element in the second slot in the array.
var str_len = myStr.length
var my_array = [myStr.slice(0, str_len/2), myStr.slice(str_len/2, str_len)]

Check string starting with substring using regex

Trying to check if randomString starting with just. (including the dot).
This should give me false but it's not the case:
var randomString = 'justanother.string';
var a = randomString.match('^just\.');
console.log(a);
I probably missed something in the regex argument.
You need to use create a Regular Expression and the use .test() method.
var randomString = 'justanother.string';
var a = /^just\./.test(randomString)
console.log(a);
The answer is simple, you didn't create regex propertly.
'this is not regex'
/this is regex/
new RexExp('this is also regex')
var randomString = 'justanother.string';
var a = randomString.match(/^just\./);
console.log(a);
// I sugest dooing something like this
const startsWithJust = (string) => /^just\./.test(string)
var randomString = 'justanother.string';
var another = 'just.....................';
console.log( randomString.match('^(just[.]).*') );
console.log( another.match('^just[.].*') );
If you wish to keep your lines the same only one change is needed.
var a = randomString.match('^just\\.');
you need to escape the first backslash.

Search through string with Javascript

Say I have a string like this:
jJKld-xxx-JKl122
Using javascript, how can I get on what's in-between the - characters? In others words, all I need to do is put whatever is xxx into a variable.
Thanks
If the string is always in that format, this will work:
var foo = 'jJKld-xxx-JKl122';
var bar = foo.split('-')[1]; // = xxx
just try it with this simple regex
var str = 'jJKld-xxx-JKl122';
var xxx = str.replace( /^[^\-]*-|-[^\-]*$/g, '' );
You can simply use the following regex to get the result
var myString = "jJKld-xxx-JKl122";
var myRegexp = /(?:^|\s*)-(.*?)-(?:^|\s*)/g;
var match = myRegexp.exec(myString);
alert(match[1]);
See the demo here

javascript retrieve value from JSON object by matching key using Regex

I have the following javascript object literal (excerpt)
var foo = {"hello[35]":100,"goodbye[45]":42};
I have the following query:
var query = "hello"
I would like to call foo[query] to obtain the value 100, but there is a [35] for which I don't necessarily know the value of. I know for sure that I will get a unique match. Is there any way to input query is some kind of javascript regular expression? i.e.
Regex = /hello/
foo[Regex]
100
pardon the noob question...
What you have here:
var foo = {"hello[35]":100,"goodbye[45]":42};
is not JSON, which is a string representation of an object; what you have is an object literal, which creates an actual JavaScript object. As far as I know the only way to retrieve a value from an object by matching a property name with a regex is to enumerate the property names and test each one. The regex you'll need is something like:
/^hello(\[\d*\])?$/
...which will match against "hello" optionally followed by zero or more digits in square brackets. But you don't want to hard code "hello" given that you also (presumably) need the "goodbye" value, so use a function:
function getPropertyByRegex(obj,propName) {
var re = new RegExp("^" + propName + "(\\[\\d*\\])?$"),
key;
for (key in obj)
if (re.test(key))
return obj[key];
return null; // put your default "not found" return value here
}
var foo = {"hello[35]":100,"goodbye[45]":42};
alert(getPropertyByRegex(foo, "hello")); // 100
alert(getPropertyByRegex(foo, "goodbye")); // 42
alert(getPropertyByRegex(foo, "whatever")); // null (not found)
Demo: http://jsfiddle.net/asDQm/
Not sure if you can use regex without any plugins or so ...
This might help already ...
var foo = {"hello[35]":100,"goodbye[45]":42};
var query = "hello";
for(var key in foo){
if (key.indexOf(query) > -1)
document.write(foo[key]);
}
http://jsfiddle.net/3qqSr
I am noob here too but I have seen this page previously see it helps you with your question. It basically explains JSon path. Also see this question.
As your JSON is a string, you can use a regexp with this kind of statement:
var foo = '{"hello[35]":100,"goodbye[45]":42}';
var result = foo.match(/"hello\[\d*\]":\d*/g);
result = result[0].split(":")[1];
alert(result);
See it live on jsfiddle
Note that you could use a var instead of "hello" in your regexp.
var foo = {"hello[35]":100,"goodbye[45]":42};
foo = foo.replace(/\[\d+\]/g,'');
var obj = (new Function("return "+foo))();
obj.hello -> 100
obj.goodbye -> 42
var query = 'hello';
obj[query] -> 100
function getVal(s, q){
var r = s.match(new RegExp(q + "\\[\\d*\\]\":(\\d*)[\\,\\}]"));
return r?r.pop():false;
}
getVal(foo, "hello")

remove parts of string with javascript

I have somewhat of an odd situation, where I need to fix a bug in a website where, when a string is created (dynamically) it adds 5 spaces before the string and 5 spaces after the string. Obviously, the best thing to do would be to fix the back end code and get rid of those spaces... long story short, I can't and I have to do it with javascript. I'm not quite sure how to do it, but this is what I was thinking
<!--Dynamically generated string including spaces added in backend-->
<span id="balance"> 245.34 </span>
My idea was to do the following with javascript
function removespace()
{
var oldString = document.getElementById('balance');
var newString = (THIS IS WHERE I AM STUCK... I NEED TO REMOVE THE SPACES);
document.getElementByID('balance').innerHTML = newString;
}
Does anyone have any suggestions?
Thanks!
ALSO FORGOT TO MENTION: I can't use any javascript libraries like prototype or jquery.
Edit: I have this so far... but it doesn't seem to be working:
<span id="balance"> $245.00 </span>
<script>
function removespace()
{
var oldString = document.getElementById('balance');
var newString = oldString.trim ();
document.getElementByID('balance').innerHTML = newString;
}
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
</script>
here is the solution I used... I finished it before I saw the other updates... but everyone was very helpful
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,"");
}
var oldString = document.getElementById('balance').innerHTML;
var newString = trim(oldString);
document.getElementById('balance').innerHTML = newString;
Unfortunetly JavaScript does not have a trim() function. But you can roll your own:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
and then do:
var newString = oldString.trim ();
the above function is from this website (first result on google for "javascript trim")
edit (based on your update to your question and comments):
change
var oldString = document.getElementById('balance');
to
var oldString = document.getElementById('balance').innerHTML;
and change
document.getElementByID('balance').innerHTML = newString;
to
document.getElementById('balance').innerHTML = newString; // notice the lower case d
and you have to call the removespace function at some point (but I'm sure you already do that) :)
Writting out of my head here.
var elem = doc.getElementById('balance');
var oldString = elem.innerHTML;
elem.innerHTML=oldString.(/^\s+|\s+$/g,"")
Something like that?
Edit: yep, only my first space is deleted, so I stole the whitespace from the answer number 1 :)
You try something like this
str.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, "");
use trim() to remove all white spaces
var newString = oldString.trim();
or use replace to replace white spaces with empty string:
var newString = oldString.replace(" ","");
with jQuery it's simple:
var newStr = jQuery.trim(oldStr);
If balance is meant to be a double you could convert it to a string:
var c = '1234';
d = c * 1;
then back to a string if need be by:
d = c.toString();

Categories

Resources