How to use a variable inside a string - javascript

I can take value of a span with this code:
document.getElementById("aaa:j_idt89:0:asd").innerHTML
but I want to use variable like i=1, for example like this:
i=1
document.getElementById("aaa:j_idt89:'[i]':asd").innerHTML
but it gives an error. How can I use the i variable in the string?

Use this code
document.getElementById("aaa:j_idt89:"+ i +":asd").innerHTML
Note the change I made inside. "+ i +" . You actually needed a String Concatenation.
So explaining the code.
when i = 1
"aaa:j_idt89:"+ i +":asd" = "aaa:j_idt89:"+ 1 +":asd" = "aaa:j_idt89:1:asd" = thats what you need

This should work for you:
var i = 1;
var element = document.getElementById("aaa:j_idt89:" + i + ":asd").innerHTML
you need to build your string up and to use your variable you need to concatenate it to your string like above " + i + " and it will work.

Related

Javascript - Get substring that comes after "string1" and before "string2"

When making a fetch to a certain URL, I am getting an HTML page in the format of text as I wanted.
Inside of it, there are plenty of id=(...)" and I require one of them
So I am asking, how could I get an array with all the strings that come after "id=" and before the " " "?
I made some tries such as :
var startsWith = "id="
var endsWith = "\""
var between = fullString.slice(fullString.indexOf(startsWith), fullstring.indexOf(endsWith))
but couldn't get it to work.
Any suggestions are welcome
you can use the following regex: /id=\"(.*?)\"/gmi.
The code will be as such:
fullString.match(/id=\"(.*?)\"/gmi)
The result will be an array of id="your id"
and then you can do the following:
var between = fullString.match(/id=\"(.*?)\"/gmi).map(str => str.substr(str.indexOf('id=\"') + 'id=\"'.length).slice(0, -1))
Why you dont use a plugin like jquery? Please refer to this example:
var fullString = "<y>your cool html</y>";
var $html = $(fullString);
var stuffInside = $(html).find('#yourId');
console.warn('stuffInside:', stuffInside.html());

Javascript Dynamic Variable (Random number added)

How do I create a dynamic variable in Javascript?
For example, I have:
var myAwesomeText = "Hello World!"
But now I want the varible MyAesomeText to have a random number attached to it every time the page is refreshed. So it would instead look like something like this:
var myAwesomeText12345 = "Hello World!"
And most importantly, how do I call that that new random variable back once the random number has been assigned to it? (i.e: alert(???);)
I've tried something like this, but I'm going wrong with this somewhere.
var myRnd = Math.floor(Math.random()*100000);
var myVar = "MyAwesomeText" + myRnd;
str = myVar + ' = ' + '"Hello World!"';
eval(str);
alert(str);
You can access the variable via the window object:
var myRnd = Math.floor(Math.random()*100000);
var myVar = "MyAwesomeText" + myRnd;
window[myVar] = "Hello World!";
alert(window[myVar]);
Don't use eval for this: it is slower and completely unnecessary for this problem. Also it can have unexpected side-effects if your MyAwesomeText has characters in it that have special meaning in JavaScript code, such as brackets, semi-colon, colon, comma, braces, ... etc.
Note that the notation object['prop'] gives the same result as object.prop. Since global variables are created in the window object, you can access any variable via the window.myvariable notation.
Combining these two facts, you can access global variables that have a dynamic name with window[dynamicVariableName].
eval is the way to go
var num = 10;
var string = "var a"+num +"= 'hi'"
string
// "var a10= 'hi'"
eval(string)
a10
// 'hi'
You miss one eval on the alert
var myRnd = Math.floor(Math.random()*100000);
var myVar = "MyAwesomeText" + myRnd;
str = myVar + ' = ' + '"Hello World!"';
eval(str);
alert(eval(myVar));

how to convert to array in js?

I have this string which I want to convert to an array:
var test = "{href:'one'},{href:'two'}";
So how can I convert this to an array?:
var new = [{href:'one'},{href:'two'}];
It depends where you got it from..
If possible you should correct it a bit to make it valid JSON syntax (at least in terms of the quotes)
var test = '{"href":"one"},{"href":"two"}';
var arr = JSON.parse('[' + test + ']');
Notice the " around both keys and values.
(making directly var test = '[{"href":"one"},{"href":"two"}]'; is even better)
If you could modify the original string to be valid JSON then you could do this:
JSON.parse(test)
Valid JSON:
var test = '[{"href":"one"},{"href":"two"}]';
Using jQuery:
var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
var jsonObj = $.parseJSON('[' + str + ']');
jsonObj is your JSON object.
If changing the string to be valid JSON is not an option, and you fully trust this string, and its origin then I would use eval:
var test = "{href:'one'},{href:'two'}";
var arr = eval("[" + test + "]");
On that last note, please be aware that, if this string is coming from the user, it would be possible for them to pass in malicious code that eval will happily execute.
As an extremely trivial example, consider this
var test = "(function(){ window.jQuery = undefined; })()";
var arr = eval("[" + test + "]");
Bam, jQuery is wiped out.
Demonstrated here

delete specific part of a string and add another at the end

I have this span on my website with these values.
<span>1,4,4,7,5,9,10</span>
I want to use jquery to delete the "1," (or what ever the first number is) from the beginning of the string and add ",12" at the end (or any other number instead of 12) so it would look like this:
<span>4,4,7,5,9,10,12</span>
How can I do this with jquery or java script ?
<span id="myText">1,4,4,7,5,9,10</span>
JS:
var text = $('#myText').html().split(',').slice(1);
text.push('12');
$('#myText').html(text.join(','));
http://jsfiddle.net/samliew/RD6W8/7/
$('span').text(function(i, t) {
return t.replace(/\d+,/, '') + ',12';
})
http://jsfiddle.net/dnkEV/
You can use split or regular expressions with string.replace
Here's how to use split:
var arr = '1,4,4,7,5,9,10'.split(',');
arr.shift();
arr.push('12');
var result = arr.join(',');
Or with regular expressions (not a very readable one I concede):
'1,4,4,7,5,9,10'.replace(/^\d+,(.*)$/, '$1,12')
Using DOM API, you can do this:
var tn = span.firstChild;
tn.deleteData(0, tn.data.indexOf(",") + 1);
tn.data += ",12";
http://jsfiddle.net/KMzau/
Or like this:
var tn = span.firstChild;
tn.data = tn.data.slice(tn.data.indexOf(",") + 1) + ",12";

Remove everything after a certain character

Is there a way to remove everything after a certain character or just choose everything up to that character? I'm getting the value from an href and up to the "?", and it's always going to be a different amount of characters.
Like this
/Controller/Action?id=11112&value=4444
I want the href to be /Controller/Action only, so I want to remove everything after the "?".
I'm using this now:
$('.Delete').click(function (e) {
e.preventDefault();
var id = $(this).parents('tr:first').attr('id');
var url = $(this).attr('href');
console.log(url);
}
You can also use the split() function. This seems to be the easiest one that comes to my mind :).
url.split('?')[0]
jsFiddle Demo
One advantage is this method will work even if there is no ? in the string - it will return the whole string.
var s = '/Controller/Action?id=11112&value=4444';
s = s.substring(0, s.indexOf('?'));
document.write(s);
Sample here
I should also mention that native string functions are much faster than regular expressions, which should only really be used when necessary (this isn't one of those cases).
Updated code to account for no '?':
var s = '/Controller/Action';
var n = s.indexOf('?');
s = s.substring(0, n != -1 ? n : s.length);
document.write(s);
Sample here
var href = "/Controller/Action?id=11112&value=4444";
href = href.replace(/\?.*/,'');
href ; //# => /Controller/Action
This will work if it finds a '?' and if it doesn't
May be very late party :p
You can use a back reference $'
$' - Inserts the portion of the string that follows the matched substring.
let str = "/Controller/Action?id=11112&value=4444"
let output = str.replace(/\?.*/g,"$'")
console.log(output)
It works for me very nicely:
var x = '/Controller/Action?id=11112&value=4444';
var remove_after= x.indexOf('?');
var result = x.substring(0, remove_after);
alert(result);
If you also want to keep "?" and just remove everything after that particular character, you can do:
var str = "/Controller/Action?id=11112&value=4444",
stripped = str.substring(0, str.indexOf('?') + '?'.length);
// output: /Controller/Action?
You can also use the split() method which, to me, is the easiest method for achieving this goal.
For example:
let dummyString ="Hello Javascript: This is dummy string"
dummyString = dummyString.split(':')[0]
console.log(dummyString)
// Returns "Hello Javascript"
Source: https://thispointer.com/javascript-remove-everything-after-a-certain-character/
if you add some json syringified objects, then you need to trim the spaces too... so i add the trim() too.
let x = "/Controller/Action?id=11112&value=4444";
let result = x.trim().substring(0, x.trim().indexOf('?'));
Worked for me:
var first = regexLabelOut.replace(/,.*/g, "");
It can easly be done using JavaScript for reference see link
JS String
EDIT
it can easly done as. ;)
var url="/Controller/Action?id=11112&value=4444 ";
var parameter_Start_index=url.indexOf('?');
var action_URL = url.substring(0, parameter_Start_index);
alert('action_URL : '+action_URL);

Categories