I am trying to replace all dots for comma and commas for dots and was wondering what is the best practice for doing this. If I do it sequentially, then the steps will overwrite each other.
For example:
1,234.56 (after replacing commas) --> 1.234.56 (after replacing dots) --> 1,234,56
Which is obviously not what I want.
One option I guess is splitting on the characters and joining afterwards using the opposite character. Is there an easier/better way to do this?
You could use a callback
"1,234.56".replace(/[.,]/g, function(x) {
return x == ',' ? '.' : ',';
});
FIDDLE
If you're going to replace more than two characters, you could create a convenience function using a map to do the replacements
function swap(str, swaps) {
var reg = new RegExp('['+Object.keys(swaps).join('')+']','g');
return str.replace(reg, function(x) { return swaps[x] });
}
var map = {
'.':',',
',':'.'
}
var result = swap("1,234.56", map); // 1.234,56
FIDDLE
You could do the following:
var str = '1,234.56';
var map = {',':'.','.':','};
str = str.replace(/[,.]/g, function(k) {
return map[k];
});
Working Demo
Do it in stages using placeholder text:
var foo = '1,234.56';
foo = foo
.replace(',', '~comma~')
.replace('.', '~dot~')
.replace('~comma~', '.')
.replace('~dot~', ',')
You could use a for loop. Something like:
var txt = document.getElementById("txt");
var newStr = "";
for (var i = 0; i < txt.innerHTML.length; i++){
var char = txt.innerHTML.charAt(i);
if (char == "."){
char = ",";
}else if (char == ","){
char = ".";
}
newStr += char;
}
txt.innerHTML = newStr;
Here's a fiddle:
http://jsfiddle.net/AyLQt/1/
Have to say though, #adenoeo's answer is way more slick :D
In javascript you can use
var value = '1.000.000,55';
var splitValue = value.split('.');
for (var i = 0; i < splitValue.length; i++) {
var valPart = splitValue[i];
var newValPart = valPart.replace(',', '.');
splitValue[i] = newValPart;
}
var newValue = splitValue.join(',');
console.log(newValue);
Related
I am very new to coding. I am having issue solving this following:
taking a data block ex:
1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42
and covert into something like
1963,"john, doe","Williwanka,tp",jane,4200,1300,19.63,-42
I know I can use split() and join() however having trouble sorting through the string separated by comma "," and add double quote.
let text = "00077;Jessica;Williamsburg,ky;40769;42;42;42;42";
var myArray = text.split(";");
var newText = "";
for (var i = 0; i <= myArray.length; i++) {
if (myArray.indexOf(i) == ",") {
let newText = '"' + fruits.join('","') + '"';
} else {
newText += text.index(i);
}
}
return newText
Split by semicolons, then for each part, check if it includes a comma. If it does, wrap it in quotes, otherwise, don't change it. Then join the result into a string.
const text = "1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42";
const parts = text.split(";");
const result = parts.map((p) => p.includes(",") ? `"${p}"` : p).join(",");
console.log(result);
You could use the regex /([^;]+)(?:;|$)/ and replace the first capturing group with " if it cannot be parsed to a number.
const input = "1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42",
replacer = (_, p1) => isNaN(p1) ? `"${p1}",` : `${p1},`,
output = input.replace(/([^;]+)(?:;|$)/g, replacer).slice(0, -1);
console.log(output)
While the previous answers are correctly fine, it might be hard to understand how they work for a novice programmer.
Allow me to fix give you another answer below which is based on a simple loop like the OPs original code.
let text = "00077;Jessica;Williamsburg,ky;40769;42;42;42;42";
var partsArray = text.split(";");
var newText = "";
for (var i = 0; i < partsArray.length; i++) {
let onePart = partsArray[i];
if (onePart.includes(",")) {
newText += `"${onePart}"`;
} else {
newText += onePart;
}
newText += ",";
}
console.log(newText);
I am writing a function to make slug from input.
var vslug = function (str) {
str = str.replace(/^\s+|\s+$/g, '');
str = str.toLowerCase();
var vregex = /(?:\.([^.]+))?$/;
var filename = str.replace(vregex.exec(str)[0],'');
var extension = vregex.exec(str)[1];
var from = "àáäâèéëêìíïîıòóöôùúüûñçşğ·/,:;";
var to = "aaaaeeeeiiiiioooouuuuncsg_____";
for (var i = 0; i < from.length; i++) {
console.log('before ' + str);
str = filename.replace(new RegExp(from[i], 'g'), to[i]);
console.log('after ' + str);
}
str = str.replace(/[^a-z0-9 _-]/g, '')
.replace(/\s+/g, '_')
.replace(/-+/g, '_');
if (typeof extension !== "undefined") {
return str+'.'+extension;
} else {
return str;
}
};
I can't make this part - I gone blind. Any help is appreciated..
var from = "àáäâèéëêìíïîıòóöôùúüûñçşğ·/,:;";
var to = "aaaaeeeeiiiiioooouuuuncsg_____";
for (var i = 0; i < from.length; i++) {
console.log('before ' + str);
str = filename.replace(new RegExp(from[i], 'g'), to[i]);
console.log('after ' + str);
}
filename is not changed - the variable names the same string, and the string cannot be modified. As such, each loop starts working on the original string again when it uses filename.replace...
Instead, eliminate filename (or integrate it fully) and use str = str.replace..
str = str.replace(vregex.exec(str)[0],'');
for (var i = 0; i < from.length; i++) {
str = str.replace(new RegExp(from[i], 'g'), to[i]);
// ^-- next loop gets new value
}
(Also, this could be handled with a replacement function and a map instead of n-loops and there might be a Unicode library for JavaScript available..)
An approach using a map and a replacement function might look like:
// Specify map somewhere reusable; can be built from paired arrays for simplicity.
var replacements = {"à":"a", "á":"a", .. ";":"_"}
// Object.keys is ES5, shim as needed. e.g. result: [à;á..]
var alternation = "[" + Object.keys(replacements).join("") + "]"
// This regex will match all characters we are trying to match.
var regex = new Regex(alternation, "g")
str = str.replace(regex, function (m) {
var r = replacements[m]
return r || m
})
See String.replace(regex, function)
function LetterChanges(str) {
var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (var i = 0; i < str.length; i++) {
var index = alphabet.indexOf(str[i])
if (/[a-zA-Z]/.test(str[i])) {
str = str.replace(str[i], alphabet.charAt(index + 1));
}
if (/[aeiou]/.test(str[i])) {
str = str.replace(str[i], alphabet.charAt(index + 26));
}
}
return str;
}
When I call LetterChanges("hello"), it returns 'Ifmmp' which is correct, but when "sent" is passed it returns 'ufOt' instead of 'tfOu'. Why is that?
str.replace() replaces the first occurrence of the match in the string with the replacement. LetterChanges("sent") does the following:
i = 0 : str.replace("s", "t"), now str = "tent"
i = 1 : str.replace("e", "f"), now str = "tfnt"
i = 2 : str.replace("n", "o"), now str = "tfot", then
str.replace("o", "O"), now str = "tfOt"
i = 3 : str.replace("t", "u"), now str = "ufOt"
return str
There are several issues. The main one is that you could inadvertently change the same letter several times.
Let's see what happens to the s in sent. You first change it to t. However, when it comes to changing the final letter, which is also t, you change the first letter again, this time from t to u.
Another, smaller, issue is the handling of the letter z.
Finally, your indexing in the second if is off by one: d becomes D and not E.
You can use String.replace to avoid that:
function LetterChanges(str) {
return str.replace(/[a-zA-Z]/g, function(c){
return String.fromCharCode(c.charCodeAt(0)+1);
}).replace(/[aeiou]/g, function(c){
return c.toUpperCase();
});
}
But there is still a bug: LetterChanges('Zebra') will return '[fcsb'. I assume that is not your intention. You will have to handle the shift.
Try this one:
function LetterChanges(str) {
var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var result = '';
var temp;
for (var i = 0; i < str.length; i++) {
var index = alphabet.indexOf(str[i])
if (/[a-zA-Z]/.test(str[i])) {
//str = str.replace(str[i], alphabet.charAt(index + 1));
temp= alphabet.charAt(index + 1);
index = index+1;
}
else if(str[i] == ' '){
temp = ' ';
}
if (/[aeiou]/.test(temp)) {
temp = alphabet.charAt(index + 26);
}
result += temp;
}
return result;
}
var str = 'bcd12';
str = str.replace(/[a-z]/gi, function(char) { //call replace method
char = String.fromCharCode(char.charCodeAt(0)+1);//increment ascii code of char variable by 1 .FromCharCode() method will convert Unicode values into character
if (char=='{' || char=='[') char = 'a'; //if char values goes to "[" or"{" on incrementing by one as "[ ascii value is 91 just after Z" and "{ ascii value is 123 just after "z" so assign "a" to char variable..
if (/[aeiuo]/.test(char)) char = char.toUpperCase();//convert vowels to uppercase
return char;
});
console.log(str);
Check this code sample. There is no bug in it. Not pretty straight forward but Works like a charm. Cheers!
function LetterChanges(str) {
var temp = str;
var tempArr = temp.split("");//Split the input to convert it to an Array
tempArr.forEach(changeLetter);/*Not many use this but this is the referred way of using loops in javascript*/
str = tempArr.join("");
// code goes here
return str;
}
function changeLetter(ele,index,arr) {
var lowerLetters ="abcdefghijklmnopqrstuvwxyza";
var upperLetters ="ABCDEFGHIJKLMNOPQRSTUVWXYZA";
var lowLetterArr = lowerLetters.split("");
var upLetterArr = upperLetters.split("");
var i =0;
for(i;i<lowLetterArr.length;i++){
if(arr[index] === lowLetterArr[i]){
arr[index] = lowLetterArr[i+1];
arr[index]=arr[index].replace(/[aeiou]/g,arr[index].toUpperCase());
return false;
}
if(arr[index] === upLetterArr[i]){
arr[index] = upLetterArr[i+1];
arr[index]=arr[index].replace(/[aeiou]/g,arr[index].toUpperCase());
return false;
}
}
}
// keep this function call here
// to see how to enter arguments in JavaScript scroll down
LetterChanges(readline());
I have a JavaScript string sentrptg2c#appqueue#sentrptg2c#vwemployees#.
I want to get last string vwemployees through RegExp or from any JavaScript function.
Please suggest a way to do this in JavaScript.
You can use the split function:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
str = str.split("#");
str = str[str.length-2];
alert(str);
// Output: vwemployees
The reason for -2 is because of the trailing #. If there was no trailing #, it would be -1.
Here's a JSFiddle.
var s = "...#value#";
var re = /#([^#]+)#^/;
var answer = re.match(s)[1] || null;
if you're sure the string will be separated by "#" then you can split on # and take the last entry... I'm stripping off the last #, if it's there, before splitting the string.
var initialString = "sentrptg2c#appqueue#sentrptg2c#vwemployees#"
var parts = initialString.replace(/\#$/,"").split("#"); //this produces an array
if(parts.length > 0){
var result = parts[parts.length-1];
}
Try something like this:
String.prototype.between = function(prefix, suffix) {
s = this;
var i = s.indexOf(prefix);
if (i >= 0) {
s = s.substring(i + prefix.length);
}
else {
return '';
}
if (suffix) {
i = s.indexOf(suffix);
if (i >= 0) {
s = s.substring(0, i);
}
else {
return '';
}
}
return s;
}
No magic numbers:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
var ar = [];
ar = str.split('#');
ar.pop();
var o = ar.pop();
alert(o);
jsfiddle example
I want to remove all empty values from an url:
var s="value1=a&value2=&value3=b&value4=c&value5=";
s = s.replace(...???...);
alert(s);
Expected output:
value1=a&value3=b&value4=c
I only need the query part of the URL to be taken into account.
Something like this:
s = s.replace(/[^=&]+=(&|$)/g,"").replace(/&$/,"");
That is, remove groups of one or more non-equals/non-ampersand characters that are followed by an equals sign and ampersand or end of string. Then remove any leftover trailing ampersand.
Demo: http://jsfiddle.net/pKHzr/
s = s.replace(/[^?=&]+=(&|$)/g,"").replace(/&$/,"");
Added a '?' to nnnnnn's answer to fix the issue where the first parameter is empty in a full URL.
This should do the trick:
var s="value1=a&value2=&value3=b&value4=c&value5=";
var tmp = s.split('&')
var newS = '';
for(var i in a) {
var t = a[i];
if(t[t.length - 1] !== '=') {
newS += t + '&';
}
}
if(newS[newS.length - 1] === '&') {
newS = newS.substr(0, newS.length - 1);
}
console.log(newS);
I don't find any solution to do that with one Regex expression.
But you could loop through your string and construct a new result string : http://jsfiddle.net/UQTY2/3/
var s="value1=a&value2=&value3=b&value4=c&value5=";
var tmpArray = s.split('&');
var final = '';
for(var i=0 ; i<tmpArray.length ; i++)
if(tmpArray[i].split('=')[1] != '')
final += tmpArray[i] + '&';
final = final.substr(0,final.length-1)
alert(final)
Where do you take all the values?
I suggest using an array:
function getValues(str){
var values = [];
var s = str.split('&');
for(var val in s){//source is a
var split = val.split('=');
if(split [1] != '' && split [1] != null){
values.push(val);
}
}
return values.join('&');
}