javascript grab part of a string after a . (dot) - javascript

I'm unable to read regex.
Let's say we have this string: "mydomain.bu.pu" and I want to grab the ".bu.pu" part of it;
I'm thinking about using something like:
indexOf and later substr ... But I confess I'm kind of lost...
Any help please? :D
Thanks in advance,
MEM

var afterDot = str.substr(str.indexOf('.'));

The above answers include the dot in the string. If you only want what's after the dot:
var afterDot = str.substr( str.indexOf('.') + 1 );

s = s.substring(s.indexOf("."));
That should do the trick.

Here is the three simple way I know.
const text = "Allah is great. Allah is only one"
const methodOne = text.split('.');
console.log(methodOne[0]); // BEFORE DOT
console.log(methodOne[1]);
const methodTwo = text.slice(text.indexOf('.')+1);
console.log(methodTwo);
const methodThree = text.substring(text.indexOf(".")+1);
console.log(methodThree)

sixCommaTwoValidation method for numeric 6,2 validation and restiction.
var afterDot = '';
var beforeDots = inputValue.split('.');
var beforeDot = beforeDots[0];
if(beforeDots[1]){
var afterDot = beforeDots[1];
if(afterDot.length > 3 ){
afterDot = afterDot.slice(0, 2);
}
afterDot = '.'+ afterDot;
}
if(beforeDot){
if(beforeDot.length > 6 ){
beforeDot = beforeDot.slice(0, 6);
}
if(beforeDots[1] == ''){
beforeDot = beforeDot + '.';
}
}
inputValue = beforeDot + afterDot;
return inputValue;

maybe this is too late to consider, but this codes works fine for me using jquery
var afterDot = value.substr(value.lastIndexOf('_') + 1);
lkjasdf_alksjd_ksdf.jpg = ksdf.jpg
aaa_bbb_ccc.jpg = ccc.jpg
testing_image.jpg = image.jpg
You could just replate '_' to '.'

Related

Javascript regex in with special character in between

Hello can anyone help my about regex. this is the string
((11A1:I19 + 11A1:K19 + 11A1:L19 + 11A1:I20 + 11A1:K20) - (11A1:N19 + 11A1:N20))
and this is the regex
/([0-9a-z])\w+:\w+([0-9-a-z])/g
I want to take 11A1:I19, 11A1:K19, etc.. and replace it with values so the string will look like this (1767+154+1123 - (151-17)) This is the full code
$f.each(function() {
var formula = $(this).data("formula");
var formula = $f.data("formula");
formula.split(/([0-9a-z])\w+:\w+([0-9-a-z])/g)
.forEach(function(el) {
if (el) {
var hy = el.split(':');
let v = $('[data-sheet="' + hy[0] + '"][data-cell="' + hy[1] + '"]').val();
formula = formula.replace(el, v);
}
});
console.log(formula)
var result = eval(formula);
$f.val(result)
});
I believe you want to do something like this (not tested with jquery)
$f.each(function() {
var formula = $(this).data("formula");
var formula = $f.data("formula");
formula.split(/([0-9a-z]+:[0-9a-z]+)/gi)
.forEach(function(el) {
if (el) {
var hy = el.split(':');
if (hy.length==2) {
let v = $('[data-sheet="' + hy[0] + '"][data-cell="' + hy[1] + '"]').val();
formula = formula.replace(el, v);
}
}
});
console.log(formula)
var result = eval(formula);
$f.val(result)
});
Update: After some more thinking, this code is more compact and possibly easier to read:
$f.each(function() {
var formula = $(this).data("formula");
var formula = $f.data("formula");
var Re=/([0-9a-z]+):([0-9a-z]+)/gi;
var hy;
var replaced=formula;
while ((hy=Re.exec(formula))!=null) {
let v = $('[data-sheet="' + hy[1] + '"][data-cell="' + hy[2] + '"]').val();
replaced = replaced.replace(hy[0], v);
}
console.log(replaced)
var result = eval(replaced);
$f.val(result)
});
For safety reasons, I would also check that v is a valid number before replacing it in the formula. That will avoid evaluating some code that might be a valid javascript expression with dire consequences. You can test it with:
if (isNaN(v+0)) continue;
Add it before replacing hy[0] with v.

Variables from div

I have this simple div:
<div id='names'>
name1[John]
name2[Blake]
name3[Sven]
name4[Ellis]
</div>
And I want to return these variables using JavaScript
var name1 = "John";
var name2 = "Blake";
var name3 = "Sven";
var name4 = "Ellis";
Your question lacks a lot of detail. Can there be more than those four names? Can't you restructure your code to get an easier access to the data?
var toParse = document.getElementById('names').innerHTML;
var m;
var re = /\[(.*)\]/g;
while (m = re.exec(toParse)) {
console.log(m[1]);
}
(https://jsfiddle.net/hL4bu5j1/)
This code looks for text in [Bracers] and outputs it to the console to give you an idea how you could approach this. You should be good to go with that. Wanted to put this as a comment but I'm not yet allowed to.
This should do it:
//document.body.innerHTML = "<div id='names'>\n name1[John]\n name2[Blake]\n name3[Sven]\n name4[Ellis]\n</div";
var obj = {};
var str = document.getElementById("names").innerHTML;
while(str.lastIndexOf(' ') >= 0) {
str=str.replace(' ','')
}
var str=str.split("\n");
for(var i = 0;i<str.length;i++){
if(str[i].length > 2) {
obj[str[i].replace(']','').split('[')[0]] = str[i].replace(']','').split('[')[1];
}
}
console.log(obj)
Here an ugly version :
var divContent = document.getElementById('names').innerHTML;
var array = divContent.trim().split(" ").filter(removeEmpty);
console.log(array)
var name1 = array[0].split('1')[1];
I think Regex suits better for your issue
https://jsfiddle.net/hrgk2s1u/

Regular Expression: how to replace a string (as a variable) that has a digit in it?

var url = 'http://mywebsite.com/?&filters[]=price_gte:20';
var path = '&filters[]=price_gte:';
var value = 10;
How do I replace the &filters[]=price_gte:20 part with the new path? (path + value)
I've tried RegExp():
var re = new RegExp(path);
console.log(url.replace(re, ''));
//returns http://mywebsite.com/?&filters[]=price_gte:20
That didn't even work, let alone adding the digit in the regex. Problem is, price_gte is a variable (and so will price_lte be, and whatever other ranges there might come), with a variable digit after it.
Information I have:
url (http://mywebsite.com?&filters[]=price_gte:20&filters[]=price_lte:100)
path (&filters[]=price_gte:)
new value (10)
Desired result:
http://mywebsite.com?&filters[]=price_gte:10&filters[]=price_lte:100
What am I missing?
You were almost there, just needed to escape the brackets:
var url = 'http://mywebsite.com/?&filters[]=price_gte:20';
var path = '&filters[]=price_gte:';
var regexPath = '&filters\\[\\]=price_gte:\\d+';
var value = 10;
var re = new RegExp(regexPath);
console.log(url.replace(re, path+value));
Perhaps you meant this
var url = 'http://mywebsite.com/?&filters[]=price_gte:20';
var path = 'filters[]=price_gte:';
var value = 10;
var re = /filters\[\]=price_[g|l]te:\d+/;
alert(url.replace(re,path+value))
However a better solution might be
// from http://stackoverflow.com/a/20420424/295783
function replaceUrlParam(url, paramName, paramValue){
var pattern = new RegExp('('+paramName+'=).*?(&|$)')
var newUrl=url
if(url.search(pattern)>=0){
newUrl = url.replace(pattern,'$1' + paramValue + '$2');
}
else{
newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
}
return newUrl
}
var url = 'http://mywebsite.com/?&filters[]=price_gte:20';
var value=10;
url = replaceUrlParam(url,"filters[]", 'price_gte:'+value);
alert(url)
This seems to work for me:
function replace() {
var url = 'http://mywebsite.com?&filters[]=price_gte:20&filters[]=price_lte:200';
var path = '&filters[]=price_gte:';
var value = 10;
var newStr = url.replace(/&filters\[\]=price_gte:\d+/, "&filters[]=price_gte:" + value);
alert(newStr);
}
This is enough for getting new value
var str = 'http://mywebsite.com?&filters[]=price_gte:20&filters[]=price_lte:100';
var pattern = /price_gte:\d+/;
var new_value = 10;
str = str.replace(patter, 'price_gte:'+new_value);
And Simple Solution will be =>
function replace() {
var url = 'http://mywebsite.com?&filters[]=price_gte:20&filters[]=price_lte:200';
var path = '&filters[]=price_gte:';
var value = 10;
var newStr = url.replace(/(\w*)(price_gte:)(\d*)/i,"price_gte:"+ value);
alert(newStr);
}

Javascript: How do I prevent reappending a string to multiple queries?

In this case, lets take YouTube as an example:
The below code, I believe, is scripted to append a string to search_query=, but it gets appended to &page= as well.
if (oSession.uriContains("www.youtube.com/results?search_query="))
{
var str = oSession.fullUrl;
var sAppend = "+test1+test2+test3";
if (oSession.fullUrl.indexOf(sAppend, str.length - sAppend.length) < 0)
{
oSession.fullUrl = str + sAppend;
}
}
Thank you in advance.
You can try this code:
if (oSession.uriContains("www.youtube.com/results?search_query="))
{
var str = oSession.fullUrl;
var sAppend = "+test1+test2+test3";
if (!oSession.uriContains(sAppend))
{
oSession.fullUrl = str + sAppend;
}
}

Replace with RegEx and JavaScript

I am attempting to do a quick replace of the 'innerHTML' of the 'code' element. I thought this may work:
function codeDisplay ( ) {
var code = document.getElementsByTagName('code').innerHTML;
var codeExam1 = new RegExp('<', 'gm');
var codeExam2 = new RegExp('>', 'gm');
code.replace(codeExam1, '<');
code.replace(codeExam2, '>');
}
Do I need to perform any additional steps to push the information back to the browser or conversion of data types maybe? Or am I completely wrong in how 'RegEx' and 'innerHTML' work? I appreciate the feedback in advance.
So, first fo all:
var code = document.getElementsByTagName('code').innerHTML;
document.getElementsByTagName returns a list of elements not just one. So, if your purpose is escaping all the code tags you have in the page, you need to iterate them.
Second, I believe you can avoid regexp just using textContent (where supported) or innerText.
var codes = document.getElementsByTagName("code");
for (var i = 0, code; code = codes[i++];) {
if ("textContent" in code)
code.textContent = code.innerHTML;
else if ("innerText" in code)
code.innerText = code.innerHTML;
}
or create a new text node:
var codes = document.getElementsByTagName("code");
for (var i = 0, code, html; code = codes[i++];) {
html = code.innerHTML;
code.innerHTML = "";
code.appendChild(document.createTextNode(html));
}
That's should escape every html entities. If you still want to use the regexp, maybe as fallback, you can have this kind of function:
var escapeEntities = (function(){
var entities = {"<" : "lt", ">" : "gt", "&" : "amp" };
var re = new RegExp("[" + Object.keys(entities).join("") + "]", "g");
function replaceEntities(match) {
return match in entities ? "&" + entities[match] + ";" : match;
}
return function(value) {
return value.replace(re, replaceEntities);
}
})()
And then in your code:
code.innerHTML = escapeEntities(code.innerHTML);
Note that if Object.keys is not supported you can easily use a shims (as indicated in the link); or simply replace manually the list of entities you support:
var entities = {"<" : "lt", ">" : "gt", "&" : "amp" };
var re = /[<>&]/g;
In that case you need to remember to add in both entities and re variables a new entity you want to support in the future; Object.keys just help you in maintenance.
Use assignment:
code = code.replace(codeExam1, '<');
code = code.replace(codeExam2, '>');
And modify your code like this:
function codeDisplay ( ) {
var codeArray = document.getElementsByTagName('code');
var codeExam1 = new RegExp('<', 'gm');
var codeExam2 = new RegExp('>', 'gm');
for ( var i = 0 ; i < codeArray.length ; ++i ){
var code = codeArray[i].innerHTML;
code.replace(codeExam1, '<');
code.replace(codeExam2, '>');
codeArray[i].innerHTML = code;
}
}
Replace returns a new string containing the result. See MDN for example.
To actually replace the contents of code you code has to look like this:
function codeDisplay ( ) {
var code = document.getElementsByTagName('code').innerHTML;
var codeExam1 = new RegExp('<', 'gm');
var codeExam2 = new RegExp('>', 'gm');
code = code.replace( codeExam1, '<');
code = code.replace(codeExam2, '>');
document.getElementsByTagName('code').innerHTML = code;
}
Or a shorter version (could be even shorter, but in my opinion just at the cost of readability):
function codeDisplay ( ) {
var code = document.getElementsByTagName('code').innerHTML;
code = code.replace( /</gm , '<' )
.replace( />/gm, '>' );
document.getElementsByTagName('code').innerHTML = code;
}
Try this:
function codeDisplay ( ) {
var s = document.getElementsByTagName('code').innerHTML;
s = s.replace(/\</g,'<');
s = s.replace(/\>/g,'>');
document.getElementsByTagName('code').innerHTML = s;
}

Categories