Match numbers in a String only once - javascript

I´ve got this code, but now I´m trying to match numbers only once.
var text = "91308543 v1_Printer 91308543 v2 91503362 v1_Printer";
var regex = /9\d{7}/g;
var result = text.match(regex);
var pos0 = result[0];
var pos1 = result[1];
var pos2 = result[2];
return(pos0 + " " + pos1 + " " + pos2);
Result is: 91308543 91308543 91503362
Result I want: 91308543 91503362
It is possible to add something to my regex so it doesn´t show duplicate values?
I prefer not to use Arrays because in that case I need to use Native Arrays...
I also have a second question, it is possible to create the variables "pos0", "pos1"... automatically?
Thank you!

The regex you are looking for is
(9\d{7})\b(?!.*\1\b)
It uses negative lookahead. See demo.
The second point is achievable through eval:
var result = text.match(regex);
for (var i = 0; i < result.length; i++){
eval('var pos' + i + ' = "' + result[i] + '"');
}
but this does not help you with the return statement.
You should just use:
return(result.join(" "));

You can filter out the duplicates after matching, and use a destructuring assingment to assign to individual variables:
let text = "91308543 v1_Printer 91308543 v2 91503362 v1_Printer";
let regex = /9\d{7}/g;
let [pos0, pos1, pos2] = text.match(regex).filter((v, i, a) => a.indexOf(v) === i);
console.log(pos0);
console.log(pos1);
console.log(pos2);

Try this pattern (9\d{7})(?!.*\1) negative lookahead .Its not allow the duplicate
Demo regex
For more reference
var text = "91308543 v1_Printer 91308543 v2 91503362 v1_Printer";
var regex = /(9\d{7})(?!.*\1)/g;
var result = text.match(regex);
console.log(result)

Related

how do i split this string into two starting from a specific position

I have this string:
var str=' "123","bankole","wale","","","","xxx" ';
I need to split this string into two. The split should start from the last comma. Resulting in:
' "123", "bankole","wale","","","" ' and ' "xxx" '
I used the below to get the "xxx":
str.split(/[,]+/).pop(); \\""
however note that the last "" can also be "something"
There are many ways to achive this.
You could split your string on commas with split(), then get the last element of the created array with slice(). Then join() the elements left in the first part back into a string.
var str = '"123", "bankole","wale","","","" and ""';
var arr = str.split(',')
var start = arr.slice(0, -1).join(',')
var end = arr[arr.length-1];
console.log(start);
console.log(end);
In the above code, the part that extracts the last part after the last comma is arr.slice(0, -1). -1 means start looking from the end of the array and go back 1.
So if you need to split from the second last, use arr.slice(0, -2)
var str = '"123", "bankole","wale","","","" and ""';
var arr = str.split(',')
var start = arr.slice(0, -2).join(',')
var end = arr.slice(-2).join(',')
console.log(start);
console.log(end);
You can simply use String.prototpye.lastIndexOf() and String.prototpye.substring()
var str='"123","bankole","wale","","","","something"';
var lastCommaIndex = str.lastIndexOf(',');
var part1 = str.substring(0, lastCommaIndex);
var part2 = str.substring(lastCommaIndex + 1, str.length);
console.log(part1)
console.log(part2)
It sounds like your regex is already what you're looking for, and that you're simply looking to extract the final segment. This can be done with array_name[array_name.length - 1], as can be seen in the following:
var str = ' "123","bankole","wale","","","","something" ';
var parts = str.split(/[,]+/);
console.log(parts[parts.length - 1]);
If you also want to remove the quotes, you can run .replace(/['"]+/g, '') on the extracted string, as is seen in the following:
var str = ' "123","bankole","wale","","","","something" ';
var parts = str.split(/[,]+/);
var extracted = parts[parts.length - 1];
console.log(extracted.replace(/['"]+/g, ''));
Hope this helps! :)
If you want to use regex you can use negative lookahead as follows.
var str = ' "123","bankole","wale","","","","something" ';
var splitResult = str.split(/,(?!.*,)/);
console.log(splitResult[0])
console.log(splitResult[1])

JavaScript Split, Split string by last DOT "."

JavaScript Split,
str = '123.2345.34' ,
expected output 123.2345 and 34
Str = 123,23.34.23
expected output 123,23.34 and 23
Goal : JS function to Split a string based on dot(from last) in O(n).
There may be n number of ,.(commas or dots) in string.
In order to split a string matching only the last character like described you need to use regex "lookahead".
This simple example works for your case:
var array = '123.2345.34'.split(/\.(?=[^\.]+$)/);
console.log(array);
Example with destructuring assignment (Ecmascript 2015)
const input = 'jquery.somePlugin.v1.6.3.js';
const [pluginName, fileExtension] = input.split(/\.(?=[^\.]+$)/);
console.log(pluginName, fileExtension);
However using either slice or substring with lastIndexOf also works, and albeit less elegant it's much faster:
var input = 'jquery.somePlugin.v1.6.3.js';
var period = input.lastIndexOf('.');
var pluginName = input.substring(0, period);
var fileExtension = input.substring(period + 1);
console.log(pluginName, fileExtension);
var str = "filename.to.split.pdf"
var arr = str.split("."); // Split the string using dot as separator
var lastVal = arr.pop(); // Get last element
var firstVal = arr.join("."); // Re-join the remaining substrings, using dot as separator
console.log(firstVal + " and " + lastVal); //Printing result
I will try something like bellow
var splitByLastDot = function(text) {
var index = text.lastIndexOf('.');
return [text.slice(0, index), text.slice(index + 1)]
}
console.log(splitByLastDot('123.2345.34'))
console.log(splitByLastDot('123,23.34.23'))
I came up with this:
var str = '123,23.34.23';
var result = str.replace(/\.([^.]+)$/, ':$1').split(':');
document.getElementById('output').innerHTML = JSON.stringify(result);
<div id="output"></div>
let returnFileIndex = str =>
str.split('.').pop();
Try this:
var str = '123.2345.34',
arr = str.split('.'),
output = arr.pop();
str = arr.join('.');
var test = 'filename.....png';
var lastStr = test.lastIndexOf(".");
var str = test.substring(lastStr + 1);
console.log(str);
I'm typically using this code and this works fine for me.
Jquery:
var afterDot = value.substr(value.lastIndexOf('_') + 1);
console.log(afterDot);
Javascript:
var myString = 'asd/f/df/xc/asd/test.jpg'
var parts = myString.split('/');
var answer = parts[parts.length - 1];
console.log(answer);
Note: Replace quoted string to your own need
My own version:
var mySplit;
var str1;
var str2;
$(function(){
mySplit = function(myString){
var lastPoint = myString.lastIndexOf(".");
str1 = myString.substring(0, lastPoint);
str2 = myString.substring(lastPoint + 1);
}
mySplit('123,23.34.23');
console.log(str1);
console.log(str2);
});
Working fiddle: https://jsfiddle.net/robertrozas/no01uya0/
Str = '123,23.34.23';
var a = Str.substring(0, Str.lastIndexOf(".")) //123,23.34
var b = Str.substring(Str.lastIndexOf(".")) //23
Try this solution.
Simple Spilt logic
<script type="text/javascript">
var str = "123,23.34.23";
var str_array = str.split(".");
for (var i=0;i<str_array.length;i++)
{
if (i == (str_array.length-1))
{
alert(str_array[i]);
}
}
</script>
The simplest way is mentioned below, you will get pdf as the output:
var str = "http://somedomain.com/dir/sd/test.pdf";
var ext = str.split('.')[str.split('.').length-1];
Output: pdf

Count occurrence times of each character in string

I have a string like this:
(apple,apple,orange,banana,strawberry,strawberry,strawberry). I want to count the number of occurrences for each of the characters, e.g. banana (1) apple(2) and strawberry(3). how can I do this?
The closest i could find was something like, which i dont know how to adapt for my needs:
function countOcurrences(str, value){
var regExp = new RegExp(value, "gi");
return str.match(regExp) ? str.match(regExp).length : 0;
}
Here is the easiest way to achieve that by using arrays.. without any expressions or stuff. Code is fairly simple and self explanatory along with comments:
var str = "apple,apple,orange,banana,strawberry,strawberry,strawberry";
var arr = str.split(','); //getting the array of all fruits
var counts = {}; //this array will contain count of each element at it's specific position, counts['apples']
arr.forEach(function(x) { counts[x] = (counts[x] || 0)+1; }); //checking and addition logic.. e.g. counts['apples']+1
alert("Apples: " + counts['apple']);
alert("Oranges: " + counts['orange']);
alert("Banana: " + counts['banana']);
alert("Strawberry: " + counts['strawberry']);
See the DEMO here
You can try
var wordCounts = str.split(",").reduce(function(result, word){
result[word] = (result[word] || 0) + 1;
return result;
}, {});
wordCounts will be a hash {"apple":2, "orange":1, ...}
You can print it as the format you like.
See the DEMO http://repl.it/YCO/10
You can use split also:
function getCount(str,d) {
return str.split(d).length - 1;
}
getCount("fat math cat", "at"); // return 3

Jquery - Add character after the first character of a string?

Say for example I have
var input = "C\\\\Program Files\\\\Need for Speed";
var output = do_it(input, ':');
Now, I would like output to have the value below :
C:\\\\Program Files\\\\Need for Speed
I need to add a character to the given string just after the first character. How can I achieve that using javascript or jquery ?
Thanks in advance
It's probably not the most efficient way, but I would do something like:
(note: this is just pseudocode)
var output = input[0] + ":" + input.substr(1, input.length);
you can use this like
String.prototype.addAt = function (index, character) {
return this.substr(0, index - 1) + character + this.substr(index-1 + character.length-1);
}
var input = "C\\Program Files\\Need for Speed";
var result = input.addAt(2, ':');
Heres one way of doing it:
Fiddle: http://jsfiddle.net/FjfB9/
var input = "C\\Program Files\\Need for Speed"
var do_it = function(str, char) {
var str = str.split(''),
temp = str.shift()
str.unshift(temp, char)
return str.join('')
}
console.log(do_it(input, ":"))

Replace last index of , with and in jQuery /JavaScript

i want to replace the last index of comma (,)in string with and.
eg . a,b,c with 'a,b and c'
eg q,w,e with q,w and e
DEMO
lastIndexOf finds the last index of the parameter string passed in it.
var x = 'a,b,c';
var pos = x.lastIndexOf(',');
x = x.substring(0,pos)+' and '+x.substring(pos+1);
console.log(x);
you can also use this function
function replace_last_comma_with_and(x) {
var pos = x.lastIndexOf(',');
return x.substring(0, pos) + ' and ' + x.substring(pos + 1);
}
console.log(replace_last_comma_with_and('a,b,c,d'));
An alternative solution using regex:
function replaceLastCommaWith(x, y) {
return x.replace(/,(?=[^,]*$)/, " " + y + " ");
}
console.log(replaceLastCommaWith("a,b,c,d", "and")); //a,b,c and d
console.log(replaceLastCommaWith("a,b,c,d", "or")); //a,b,c or d
This regex should do the job
"a,b,c,d".replace(/(.*),(.*)$/, "$1 and $2")
Try the following
var x= 'a,b,c,d';
x = x.replace(/,([^,]*)$/, " and $1");
Try
var str = 'a,b,c', replacement = ' and ';
str = str.replace(/,([^,]*)$/,replacement+'$1');
alert(str)
Fiddle Demo
A simple loop will help you out
first find the index of all , in your string using,
var str = "a,b,c,d,e";
var indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === ",") indices.push(i);
}
indices = [1,3,5,7] as it start from 0
len = indices.length()
str[indices[len - 1]] = '.'
This will solve your purpose.

Categories

Resources