How can I parse a value out of a string with javascript? - javascript

I a string name content that has inside the text "data-RowKey=xxx". I am trying to get out xxx so I tried the following:
var val = content.substring(12 + content.indexOf("data-RowKey="), 3);
This does not work at all. rather than just get three characters I get a very long string. Can anyone see what I am doing wrong

You're using wrong tool. When you want to capture a data matching some pattern, you should use regular expressions. If your value is exactly three symbols, correct expression would be /data-RowKey=(...)/ with . standing for any symbol and () specifying part to capture.

.substring() [MDN] takes two indexes, .substr() [MDN] takes an index and the length. Try:
var val = content.substr(12 + content.indexOf("data-RowKey="), 3);
If "data-RowKey=xxx" is the whole string, there are various other ways to get xxx:
var val = content.replace('data-RowKey=', '');
var val = content.split('=')[1]; // assuming `=` does not appear in xxx

This works:
var value = content.match(/data-RowKey=(.*)/)[1];
Live DEMO
If there could be values after the xxx, use this:
"data-RowKey=123abc".match(/data-RowKey=(.{3}).*/)[1] // 123

If your rowkey is numeric, this might be best since you get the number as an integer and wouldn't need to convert later:
var val = parseInt( content.split("data-RowKey=")[1] );
If always the three characters and/or no need to convert:
var val = content.split("data-RowKey=")[1].substring(0,3);

Related

Change a unique Character on jQuery

<span class="number1">10.00</span>
simply, i want to replace the '.'(dot) for a ','(comma) using jQuery.
I've tried several forms to search the $('.number1') characters and replacing
it with a comma.
<span class="number1">10.00</span>
What if there is more than one Dot in the string?
Why use jQuery for such a simple operation? What you need is a simple string manipulation. Adding a library so that you can type a few less characters to do something so basic seems hardly worth it.
What you really need the the plain old JavaScript String.replace() method.
Here's jQuery and non-jQuery ways to do it:
// With jQuery:
console.log($(".number1").text().replace(".", ","));
// Without jQuery:
console.log(document.querySelector(".number1").textContent.replace(".", ","));
// When you need to replace all the . chars. in the string, you'll need to use
// a regular expression with .replace().
// The / / denote the delimiters of a regular expression
// The \. is the escape code for a .
// The g means do a global find/replace throughout the string
// With jQuery:
console.log($(".number1").text().replace(/\./g, ","));
// Without jQuery:
console.log(document.querySelector(".number1").textContent.replace(/\./g, ","));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="number1">10.00.00</span>
Try this answer.
$(".number1").text(function () {
return $(this).text().replace(/\./g, ",");
});
this is a solution in vanilla js:
let spanNumber = document.querySelector('.number1')
let number = spanNumber.textContent
let newNumber = number.split('.').join(',')
spanNumber.innerHTML = newNumber
short version with replace:
let DOMElement = document.querySelector('.number1')
let string = DOMElement.textContent.replace('.',',')
DOMElement.innerHTML = string
Just use built in DOM property innerHTML, instead of unecessary jQuery mambo jambo like:
var num1 = document.querySelector('.number1');
num1.innerHTML = num1.innerHTML.replace('.', ',');
InnerHTML is value between your HTML tags, and since its a string it has access to all String prototype methods and properties.
Just turn it to array by finding a dot delimiter with split method, then get it right back using join like:
// Lets say that the value is 10.05.53.324.343
var num1 = document.querySelector('.number1');
num1.innerHTML = num1.innerHTML.split('.').join(','); // Outputs 10,05,53,324,343
You could use the Intl.NumberFormat object instead of replacing characters:
Perhaps you have other numbers on your content that you want to format.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
But you can check a working example below that formats a number on US-EN format to pt-BR:
var el = document.querySelector('.number1');
var value = parseFloat(el.textContent);
var newValue = new Intl.NumberFormat('pt-BR', { minimumFractionDigits: 2 }).format(value);
el.innerHTML = newValue;
<span class="number1">10.00</span>

How to get value between 2 character

I have an Id of '2015-11-30_1112_3'. How do I get the values between the two underscores(_) so I am left with '1112'.
Please note that the length of the string varies.
simplest solution would be
var value = '2015-11-30_1112_3';
alert( value.split( "_" )[ 1 ] );
just split the variable, which should give you an array of 3 items. Second item is what you are looking for
You can of course use a regular expression:
s.match(/_(.*)_/)[1]
Explanation: I assume s is your string. The expression matches everything, i.e. (.*), between two underscores. You have to select index 1 of the result because index 0 will give you the complete match including the underscores. Subsequent elements contain the bracketed groups.
You can do this if you are sure that all ids have the same format:
var str= '2015-11-30_1112_3';
var array=str.split("_");
alert(array[1]);
Write like this..
var value = "2015-11-30_1112_3";
var value1 = value.match(/_(.+)_/g);
Demo : Click here
Please try below solution with the help of this solution you can find value between two different symbols as well.
var str = "2015-11-30_1112_3";
var newStr = str.split('_')[1].split('_')[0];
alert(newStr);

How to remove comma from number which comes dynamically in .tpl file

i want to remove comma from a number (e.g change 1,125 to 1125 ) in a .tpl file.
The value comes dynamically like ${variableMap[key]}
var a='1,125';
a=a.replace(/\,/g,''); // 1125, but a string, so convert it to number
a=parseInt(a,10);
Hope it helps.
var a='1,125'
a=a.replace(/\,/g,'')
a=Number(a)
You can use the below function. This function can also handle larger numbers like 123,123,123.
function removeCommas(str) {
while (str.search(",") >= 0) {
str = (str + "").replace(',', '');
}
return str;
};
var s = '1,125';
s = s.split(',').join('');
Hope that helps.
✨ ES2021 ✨ added replaceAll, so no need for regular expression:
const str = '1,125,100.05';
const number = parseFloat(str.replaceAll(",", ""));
You can use Regular Expression to change as it is faster than split join
var s = '1,125';
s = s.replace(/,/g, '');
//output 1125
Incoming value may not always be a string. If the incoming value is a numeric the replace method won't be available and you'll get an error.
Suggest using isNaN to see if numeric, then assume string and do replacement otherwise.
if(isNaN(x)) {
x = parseInt(x.replace(/[,]/g,''));
}
(Not foolproof because 'not number' doesn't prove it is a string, but unless you're doing something very weird should be good enough).
You can also add other symbols to the character group to remove other stray chars (such as currency symbols).

regex - get numbers after certain character string

I have a text string that can be any number of characters that I would like to attach an order number to the end. Then I can pluck off the order number when I need to use it again. Since there's a possibility that the number is variable length, I would like to do a regular expression that catch's everything after the = sign in the string ?order_num=
So the whole string would be
"aijfoi aodsifj adofija afdoiajd?order_num=3216545"
I've tried to use the online regular expression generator but with no luck. Can someone please help me with extracting the number on the end and putting them into a variable and something to put what comes before the ?order_num=203823 into its own variable.
I'll post some attempts of my own, but I foresee failure and confusion.
var s = "aijfoi aodsifj adofija afdoiajd?order_num=3216545";
var m = s.match(/([^\?]*)\?order_num=(\d*)/);
var num = m[2], rest = m[1];
But remember that regular expressions are slow. Use indexOf and substring/slice when you can. For example:
var p = s.indexOf("?");
var num = s.substring(p + "?order_num=".length), rest = s.substring(0, p);
I see no need for regex for this:
var str="aijfoi aodsifj adofija afdoiajd?order_num=3216545";
var n=str.split("?");
n will then be an array, where index 0 is before the ? and index 1 is after.
Another example:
var str="aijfoi aodsifj adofija afdoiajd?order_num=3216545";
var n=str.split("?order_num=");
Will give you the result:
n[0] = aijfoi aodsifj adofija afdoiajd and
n[1] = 3216545
You can substring from the first instance of ? onward, and then regex to get rid of most of the complexities in the expression, and improve performance (which is probably negligible anyway and not something to worry about unless you are doing this over thousands of iterations). in addition, this will match order_num= at any point within the querystring, not necessarily just at the very end of the querystring.
var match = s.substr(s.indexOf('?')).match(/order_num=(\d+)/);
if (match) {
alert(match[1]);
}

Regular expression in Javascript (without jQuery)?

I am new to Javascript and recently I wanted to use regular expression in order to get a number from url and store it into a var as string and another var as digit. For example I want to get the number 55 from the below webpage (which is not an accrual page) and I want to store it in a var.
I tried this but it is not working
https://www.google.com/55.html
url.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
return((Number(p1) + 1) + p2);
Please I need help but not with jQuery because it does not make a lot of sense to me.
var numPortion = url.match(/(\d+)\.html/)[1]
(Assumes a match; if it might not match, check the results before applying the array subscript.)
Try this
var a="https://www.google.com/55.html";
var match = a.match(/(\d+)(\.html)/);
match is an array,
match[0] contains the matched expression from your script,
match[1] is the number (the 1st parenthesis),
and so on
var url = 'http://www.google.com/55.html';
var yournumber = /(\d+)(\.html)$/.exec(url);
yournumber = yournumber && yournumber[1]; // <-- shortcut for using if else

Categories

Resources