So using jquery and I have a string of coordinates like so:
38.313072,-89.863845,38.312675,-89.863586,38.310405,-89.862091,38.310405,-89.862091,38.309913,-89.861976,38.309768,-89.861976,38.309768,-89.861976
I need them to look like this:
[38.313072, -89.863845] [38.312675, -89.863586] [38.310405, -89.862091] [38.310405,-89.862091] [38.309913, -89.861976] [38.309768, -89.861976] [38.309768, -89.861976] [38.30965, -89.861991]
So I need to figure out how to replace every other comma with a space and bracket sets of coordinates.
Ideas?
You can use regex.
([-\d.]+),([-\d.]+),?
Regex Explanation and Live Demo
[-\d.]: Character class, - will match literal - hyphen, \d will match a single digit, . will match . literally. When mentioned inside class sequence doesn't matter.
+: Matches one or more occurrences of the previous matches
(...): Capturing Group. The matches inside the braces are captured and returned in $1, $2, ...
,?: To not match the every other comma
g: Global Match. To match all possible occurrences.
jsFiddle Demo
var str = '38.313072,-89.863845,38.312675,-89.863586,38.310405,-89.862091,38.310405,-89.862091,38.309913,-89.861976,38.309768,-89.861976,38.309768,-89.861976';
var result = str.replace(/([-\d.]+),([-\d.]+),?/g, '[$1, $2] ').trim();
document.getElementById('output').innerHTML = JSON.stringify(result, 0, 2);
<pre id="output"></pre>
Use Regex !
It's perfect for this !
var str = "38.313072,-89.863845,38.312675,-89.863586,38.310405,-89.862091,38.310405,-89.862091,38.309913,-89.861976,38.309768,-89.861976,38.309768,-89.861976,38.30965, -89.861991";
var expected = "[38.313072, -89.863845] [38.312675, -89.863586] [38.310405, -89.862091] [38.310405,-89.862091] [38.309913, -89.861976] [38.309768, -89.861976] [38.309768, -89.861976] [38.30965, -89.861991]"
var computed = str.replace(/(([0-9\-. ]*)(,)([0-9\-. ]*)),?/g, '[$2 $3 $4] ');
document.write('computed<br>')
document.write(str.replace(/(([0-9\-. ]*)(,)([0-9\-. ]*)),?/g, '[$2 $3 $4] '))
document.write( "<hr>expected<br>" + expected )
Not pretty, but it works:
var coordinateString = "38.313072,-89.863845,38.312675,-89.863586,38.310405,-89.862091,38.310405,-89.862091,38.309913,-89.861976,38.309768,-89.861976,38.309768,-89.861976";
var coordinateArray = coordinateString.split(",");
var coordinateResult = "";
var i = 0;
while(i<coordinateArray.length){
coordinateResult +="[" + coordinateArray[i] + ", " + coordinateArray[i+1] + "]";
i += 2;
}
This should do the work.
function toPairs(src){
// Split the string into values.
var values = src.split(',');
// Group these values 2 by 2.
var pairs = [];
for(var i = 0; i < values.length; i += 2){
pairs.push("[" + values[i] + ", " + values[i + 1] + "]");
}
// Join with a whitespace.
return pairs.join(" ");
}
document.body.innerHTML = toPairs("38.313072,-89.863845,38.312675,-89.863586,38.310405,-89.862091,38.310405,-89.862091,38.309913,-89.861976,38.309768,-89.861976,38.309768,-89.861976");
Try utilizing while loop , Array.prototype.splice() , returning results as array of arrays
var str = "38.313072,-89.863845,38.312675,-89.863586,38.310405,-89.862091,38.310405,-89.862091,38.309913,-89.861976,38.309768,-89.861976,38.309768,-89.861976"
, res = []
, arr = str.split(",");
while (arr.length) res.push(arr.splice(0, 2))
console.log(res, JSON.stringify(res, null, 2))
Related
I have a regEx where I replace everything whats not a number:
this.value.replace(/[^0-9\.]/g,'');
how can i make sure it will only allow 1 dot
(the second dot will be replaced like the others)
(I know you can use input just number (thats not an option in this project for me))
You can use a simple trick of:
splitting a string by ., and then only joining the first two elements of the array (using .splice(0,2)) with a . and the rest with nothing
using a simple regex pattern to replace all non-digit and non-period characters: /[^\d\.]/gi
Here is an example code:
// Assuming that `yourString` is the input you want to parse
// Step 1: Split and rejoin, keeping only first occurence of `.`
var splitStr = yourString.split('.');
var parsedStr = splitStr[0];
if (splitStr.length) {
parsedStr = splitStr.splice(0, 2).join('.') + splitStr.join('');
}
// Step 2: Remove all non-numeric characters
parsedStr = parsedStr.replace(/[^\d\.]/gi, '');
Proof-of-concept example:
var tests = [
'xx99',
'99xx',
'xx99xx',
'xxxx999.99.9xxx',
'xxxx 999.99.9 xxx',
'xx99xx.xx99xx.x9',
'xx99xx.99x.9x',
'xx99.xx99.9xx'
];
for (var i = 0; i < tests.length; i++) {
var str = tests[i];
// Split and rejoin, keeping only first occurence of `.`
var splitStr = str.split('.');
var parsedStr = splitStr[0];
if (splitStr.length) {
parsedStr = splitStr.splice(0, 2).join('.') + splitStr.join('');
}
// Remove all non-numeric characters
parsedStr = parsedStr.replace(/[^\d\.]/gi, '');
console.log('Original: ' + str + '\nParsed: ' + parsedStr);
}
I resolved it with.
this.value = this.value.replace(/.*?(\d+.\d+).*/g, "$1");
I need to capitalize all letters in the beginning of a string, all letters before the first number that appears in the string.
abc123 will be ABC123
abc123def will be ABC123def
First I find the index of the first number in the string:
var index = myString.search(/\d/);
Then I have a for loop where I try to change every letter before that number:
for (var i=0; i<index; i++) {
myString = myString.charAt(i).toUpperCase() + myString.slice(i+1);
}
The problem is that the code removes the letter in the beginning in every loop.
How can I do it better?
Thank you for your help
You can do it by the code below:
var str = "abc23mlk";
var index = str.search(/\d/);
if (index !== -1) {
str = str.slice(0, index).toUpperCase() + str.slice(index);
}
console.log(str);
You can use a regex and a replacer function:
function replace(text) {
return text.replace(/[a-z]+(?=\d)/i, function(match) {
return match.toUpperCase();
});
}
["abc123", "abc123def", "abcd12efgh34ijkl"].forEach(function(test) {
console.log("'" + test + "' becomes '" + replace(test) + "'");
});
The regex /[a-z]+(?=\d)/i looks for the first sequence of letters ([a-z]+) that is immediately followed by a digit ((?=\d) here as a positive look-ahead so it is not matched).
You also do something like
Find the index as how you are doing now
Substring and capitalize
Slice and append
var myString = "abc123"
var index = myString.search(/\d/);
myString = myString.substr(0,index).toUpperCase() + myString.slice(index);
I'm working to update this function which currently takes the content and replaces any instance of the target with the substitute.
var content = textArea.value; //should be in string form
var target = targetTextArea.value;
var substitute = substituteTextArea.value;
var expression = new RegExp(target, "g"); //In order to do a global replace(replace more than once) we have to use a regex
content = content.replace(expression, substitute);
textArea.value = content.split(",");
This code somewhat works... given the input "12,34,23,13,22,1,17" and told to replace "1" with "99" the output would be "992,34,23,993,22,99,997" when it should be "12,34,23,13,22,99,17". The replace should only be performed when the substitute is equal to the number, not a substring of the number.
I dont understand the comment about the regex needed to do a global replace, I'm not sure if that's a clue?
It's also worth mentioning that I'm dealing with a string separated by either commas or spaces.
Thanks!
You could do this if regex is not a requirement
var str = "12,34,23,13,22,1,17";
var strArray = str.split(",");
for(var item in strArray)
{
if(strArray[item] === "1")
{
strArray[item] = "99"
}
}
var finalStr = strArray.join()
finalStr will be "12,34,23,13,22,99,17"
Try with this
var string1 = "12,34,23,13,22,1,17";
var pattern = /1[^\d]/g;
// or pattern = new RegExp(target+'[^\\d]', 'g');
var value = substitute+",";//Replace comma with space if u uses space in between
string1 = string1.replace(pattern, value);
console.log(string1);
Try this
target = target.replace(/,1,/g, ',99,');
Documentation
EDIT: When you say: "a string separated by either commas or spaces"
Do you mean either a string with all commas, or a string with all spaces?
Or do you have 1 string with both commas and spaces?
My answer has no regex, nothing fancy ...
But it looks like you haven't got an answer that works yet
<div id="log"></div>
<script>
var myString = "12,34,23,13,22,1,17";
var myString2 = "12 34 23 13 22 1 17";
document.getElementById('log').innerHTML += '<br/>with commas: ' + replaceItem(myString, 1, 99);
document.getElementById('log').innerHTML += '<br/>with spaces: ' + replaceItem(myString2, 1, 99);
function replaceItem(string, needle, replace_by) {
var deliminator = ',';
// split the string into an array of items
var items = string.split(',');
// >> I'm dealing with a string separated by either commas or spaces
// so if split had no effect (no commas found), we try again with spaces
if(! (items.length > 1)) {
deliminator = ' ';
items = string.split(' ');
}
for(var i=0; i<items.length; i++) {
if(items[i] == needle) {
items[i] = replace_by;
}
}
return items.join(deliminator);
}
</script>
How to find multiple values within curly braces from a string using JavaScript.
E.g.
string = https://test.com/tour/reception/#{name1}/#{name2}/test/#{name3};
I tried with this, /#{[A-Za-z0-9À-ÿ_ .-]*}/ but don't know how to get the values matched.
How can you get the name1, name2 and name3 from the string?
Use a regex to match text surrounded by curly braces. You'll want to use +? to match non-greedily.
var string = "https://test.com/tour/reception/#{name1}/#{name2}/test/#{name3}";
var matches = string.match(/{.+?}/g);
Now matches is ["{name1}", "{name2}", "{name3}"].
You can use this RegEx.
/{.*?}/g
E.g.
var s = 'https://test.com/tour/reception/#{name1}/#{name2}/test/#{name3};';
var res = s.match(/{.*?}/g);
for (var r in res)
{
console.log(res[r]);
}
This outputs
{name1}
{name2}
{name3}
While other answers show how to extract the text with curly brackets, none of them has really answered the question.
How can you get the name1, name2 and name3 from the string?
You can use String#indexOf and String#substring methods.
var str = "https://test.com/tour/reception/#{name1}/#{name2}/test/#{name3};";
// Copy the string
var copy = str;
var index,
matches = []; // To store results
// Till there is string wrapped in curly braces
while ((index = copy.indexOf('{')) !== -1) {
var closingIndex = copy.indexOf('}');
matches.push(copy.substring(index + 1, closingIndex));
// Update the string to remove the first match
copy = copy.substring(closingIndex + 1);
}
console.log(matches);
document.body.innerHTML = '<pre>' + JSON.stringify(matches, 0, 4) + '</pre>';
Using RegEx
/{([^}]*)}/
With global flag.
Regex101 Demo
RegEx Explanation:
{: Match { literally
([^}]*): Match anything that is not } any number of times and put the match result in the first captured group.
}: Match closing bracket }
g: Global flag
In JavaScript, get the results by using RegExp#exec.
var regex = /{([^}]*)}/g;
var str = "https://test.com/tour/reception/#{name1}/#{name2}/test/#{name3};";
var matches = [];
while (match = regex.exec(str)) {
// match[1] is the first captured group
matches.push(match[1]);
}
console.log(matches);
document.body.innerHTML = '<pre>' + JSON.stringify(matches, 0, 4) + '</pre>';
If you want a non-regex syntax (perhaps for more clarity):
var str = "https://test.com/tour/reception/#{name1}/#{name2}/test/#{name3}";
var bopen = false;
var valIndex = {
istart: 0,
iend: 0
};
values = [];
for (var i = 0 ; i < str.length ; i++) {
var ch = str.charAt(i);
if (ch == '{') {
bopen = true;
valIndex.istart = i;
}
if (ch == '}' && bopen == true){
bopen = false;
valIndex.iend = i;
values.push(str.substring(valIndex.istart + 1, valIndex.iend));
}
}
alert(values);
The alerted result is an array of strings : name1,name2,name3
Here's a JSFiddle.
I'm looking for a regex that will remove all characters that have been repeated in a string. I already solved this using a loop. Just wondering if there is a regex that can do the same.
this is what i have so far:
function onlyUnique(str) {
var re = /(.)(?=.*\1)/g
return str.replace(re, '');
}
This string:
"rc iauauc!gcusa_usdiscgaesracg"
should end up as this:
" !_de"
You can use Array#filter with Array#indexOf and Array#lastIndexOf to check if the element is repeated.
var str = "rc iauauc!gcusa_usdiscgaesracg";
// Split to get array
var arr = str.split('');
// Filter splitted array
str = arr.filter(function (e) {
// If index and lastIndex are equal, the element is not repeated
return arr.indexOf(e) === arr.lastIndexOf(e);
}).join(''); // Join to get string from array
console.log(str);
document.write(str);
well, no idea if regex can do that, but you could work it out using for loop, like:
function unikChars(str) {
store = [];
for (var a = 0, len = str.length; a < len; a++) {
var ch = str.charAt(a);
if (str.indexOf(ch) == a && str.indexOf(ch, a + 1) == -1) {
store.push(ch);
}
}
return store.join("");
}
var str = 'rc iauauc!gcusa_usdiscgaesracg';
console.log(unikChars(str)); //gives !_de
Demo:: jsFiddle
Your regex searches pairs of duplicated characters and only removes the first one. Therefore, the latest duplicate won't be removed.
To address this problem, you should remove all duplicates simultaneously, but I don't think you can do this with a single replace.
Instead, I would build a map which counts the occurrences of each character, and then iterate the string again, pushing the characters that appeared only once to a new string:
function onlyUnique(str) {
var map = Object.create(null);
for(var i=0; i<str.length; ++i)
map[str[i]] = (map[str[i]] || 0) + 1;
var chars = [];
for(var i=0; i<str.length; ++i)
if(map[str[i]] === 1)
chars.push(str[i]);
return chars.join('');
}
Unlike indexOf, searches in the hash map are constant on average. So the cost of a call with a string of n characters will be n.
If you want to do it with a regex, you can use your own regex with a callback function inside a replace.
var re = /(.)(?=.*\1)/g;
var str = 'rc iauauc!gcusa_usdiscgaesracg';
var result = str;
str.replace(re, function(m, g1) {
result = result.replace(RegExp(g1.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"), '');
});
document.getElementById("r").innerHTML = "'" + result + "'";
<div id="r"/>
The idea is: get the duplicated character, and remove it from the input string. Note that escaping is necessary if the character might be a special regex metacharacter (thus, g1.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") is used).
Another idea belongs to Washington Guedes in his deleted answer, I just add my own implementation here (with removing duplicate symbols from the character class and escaping special regex chars):
var s = "rc iauauc!gcusa_u]sdiscgaesracg]";
var delimiters= '[' + s.match(/(.)(?=.*\1)/g).filter(function(value, index, self) { // find all repeating chars
return self.indexOf(value) === index; // get unique values only
}).join('').replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + ']'; // escape special chars
var regex = new RegExp(delimiters, 'g'); // build the global regex from the delimiters
var result = s.replace(regex, ''); // obtain the result
document.getElementById("r2").innerHTML = "'" + result + "'";
<div id="r2"/>
NOTE: if you want to support newline symbols as well, replace . with [^] or [\s\S] inside the regex pattern.
function onlyUnique(str) {
// match the characters you want to remove
var match = str.match(/(.)(?=.*\1)/g);
if (match) {
// build your regex pattern
match = '[' + match.join('') + ']';
}
// if string is already unique return the string
else {
return str
}
// create a regex with the characters you want to remove
var re = new RegExp(match, 'g');
return str.replace(re, '');
}