Change a unique Character on jQuery - javascript

<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>

Related

String Remove in Jquery

I want to remove - from a string
myString = 12-132-232-1213-3
I have already tried
myString.replace('-','');
But this would replace only the first charcter 12132-232-1213-3, but iam expecting 1213223212133 how to fix this?
You can specify it using the pattern /-/ with the global modifier g as follows:
myString.replace(/-/g, '');
// => "1213223212133"
This is because you have not assigned the value. Try like this and let me know.
myString = myString.replace('/-/g','');
There is two methods for remove/replace string in jQuery.
var myString = "12-132-232-1213-3";
1 myString = myString.replace('-','').replace('-','').replace('-','').replace('-','');
Here you can see .replace('-','') is use four times because we want to replace four times - in your string.
2 myString = myString.replace(/-/g,''); is more reliable to first one.
After see both method then most usefull mothod is 2. Because there is no repeated code for replace('-','')

Grab the end of a URL after the last slash with regex in javascript

I need to be able to grab the number at the end of the url, and set it as the value of a textbox. I have the following, but it's not correctly stripping out the beginning of the URL before the last slash. Instead, its doing the opposite.
<input id="imageid"></input>
var referrerURL = "http://subdomain.xx-xxxx-x.xxx.url.com/content/assets/750";
var assetID = referrerURL.match("^(.*[\\\/])");
$("#imageid").val(assetID);
The result of the regex match should set the value of the text box to 750 in this case.
JSFiddle: Link
The simple method is to use a negated character class as
/[^\/]*$/
Regex Demo
Example
var referrerURL = "http://subdomain.xx-xxxx-x.xxx.url.com/content/assets/750";
alert(referrerURL.match(/[^\/]*$/));
// Output
// => 750
Can use a simple split() and then pop() the resultant array
var assetID = referrerURL.split('/').pop();
Easier to read than a regex thus very clear what it is doing
DEMO
var referrerURL = "http://subdomain.xx-xxxx-x.xxx.url.com/content/assets/750";
var myregexp = /.*\/(.*?)$/;
var match = myregexp.exec(referrerURL);
$("#imageid").val(match[1]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="imageid"></input>
You could try avoiding the usage of regular expression for this task just by using native javascript's string functions.
Splitting the text:
var lastSlashToken = referrerURL.split("/").pop(-1);
Looking up for the last ending "/text" token:
var lastSlashToken = referrerURL.substr(referrerURL.lastIndexOf("/") + 1);
However, if you still want to use regular expression for this task, you could try using the following pattern:
.*\/([^$]+)
Working DEMO example # regex101

How can I parse a value out of a string with 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);

Javascript regexp replace, multiline

I have some text content (read in from the HTML using jQuery) that looks like either of these examples:
<span>39.98</span><br />USD
or across multiple lines with an additional price, like:
<del>47.14</del>
<span>39.98</span><br />USD
The numbers could be formatted like
1,234.99
1239,99
1 239,99
etc (i.e. not just a normal decimal number). What I want to do is get just whatever value is inside the <span></span>.
This is what I've come up with so far, but I'm having problems with the multiline approach, and also the fact that there's potentially two numbers and I want to ignore the first one. I've tried variations of using ^ and $, and the "m" multiline modifier, but no luck.
var strRegex = new RegExp(".*<span>(.*?)</span>.*", "g");
var strPrice = strContent.replace(strRegex, '$1');
I could use jQuery here if there's a way to target the span tag inside a string (i.e. it's not the DOM we're dealing with at this point).
You could remove all line breaks from the string first and then run your regex:
strContent = strContent.replace(/(\r\n|\n|\r)/gm,"");
var strRegex = new RegExp(".*<span>(.*?)</span>.*", "g");
var strPrice = strContent.replace(strRegex, '$1');
This is pretty easy with jQuery. Simply wrap your HTML string inside a div and use jQuery as usual:
var myHTML = "<span>Span 1 HTML</span><span>Span 2 HTML</span><br />USD";
var $myHTML = $("<div>" + myHTML + "</div>");
$myHTML.find("span").each(function() {
alert($(this).html());
});
Here's a working fiddle.
try using
"[\s\S]*<span>(.*?)</span>[\s\S]*"
instead of
".*<span>(.*?)</span>.*"
EDIT: since you're using a string to define your regex don't forget to esacpe your backslashes, so
[\s\S]
would be
[\\s\\S]
You want this?
var str = "<span>39.98</span><br />USD\n<del>47.14</del>\n\n<span>40.00</span><br />USD";
var regex = /<span>([^<]*?)<\/span>/g;
var matches = str.match(regex);
for (var i = 0; i < matches.length; i++)
{
document.write(matches[i]);
document.write("<br>");
}
Test here: http://jsfiddle.net/9LQGK/
The matches array will contain the matches. But it isn't really clear what you want. What does there's potentially two numbers and I want to ignore the first one means?

Strip all non-numeric characters from string in JavaScript

Consider a non-DOM scenario where you'd want to remove all non-numeric characters from a string using JavaScript/ECMAScript. Any characters that are in range 0 - 9 should be kept.
var myString = 'abc123.8<blah>';
//desired output is 1238
How would you achieve this in plain JavaScript? Please remember this is a non-DOM scenario, so jQuery and other solutions involving browser and keypress events aren't suitable.
Use the string's .replace method with a regex of \D, which is a shorthand character class that matches all non-digits:
myString = myString.replace(/\D/g,'');
If you need this to leave the dot for float numbers, use this
var s = "-12345.50 €".replace(/[^\d.-]/g, ''); // gives "-12345.50"
Use a regular expression, if your script implementation supports them. Something like:
myString.replace(/[^0-9]/g, '');
You can use a RegExp to replace all the non-digit characters:
var myString = 'abc123.8<blah>';
myString = myString.replace(/[^\d]/g, ''); // 1238
Something along the lines of:
yourString = yourString.replace ( /[^0-9]/g, '' );
Short function to remove all non-numeric characters but keep the decimal (and return the number):
parseNum = str => +str.replace(/[^.\d]/g, '');
let str = 'a1b2c.d3e';
console.log(parseNum(str));
In Angular / Ionic / VueJS -- I just came up with a simple method of:
stripNaN(txt: any) {
return txt.toString().replace(/[^a-zA-Z0-9]/g, "");
}
Usage on the view:
<a [href]="'tel:'+stripNaN(single.meta['phone'])" [innerHTML]="stripNaN(single.meta['phone'])"></a>
The problem with these answers above, is that it assumes whole numbers. But if you need a floating point value, then the previous reg string will remove the decimal point.
To correct this you need write a negated character class with ^
var mystring = mystring.replace(/[^0-9.]/g, '');
try
myString.match(/\d/g).join``
var myString = 'abc123.8<blah>'
console.log( myString.match(/\d/g).join`` );
Unfortunately none of the answers above worked for me.
I was looking to convert currency numbers from strings like $123,232,122.11 (1232332122.11) or USD 123,122.892 (123122.892) or any currency like ₹ 98,79,112.50 (9879112.5) to give me a number output including the decimal pointer.
Had to make my own regex which looks something like this:
str = str.match(/\d|\./g).join('');
This,
.match(/\d|\.|\-/g).join('');
Handles both , and . also -
Example:
"Balance -$100,00.50".match(/\d|\.|\-/g).join('');
Outputs
10000.50
we are in 2017 now you can also use ES2016
var a = 'abc123.8<blah>';
console.log([...a].filter( e => isFinite(e)).join(''));
or
console.log([...'abc123.8<blah>'].filter( e => isFinite(e)).join(''));
The result is
1238

Categories

Resources