I know how to find the first occurence of a predefined character like so a.indexOf("R") but what if you would like to find the first occurence of any character A-Z, say that my string contains digits and other special characters and I'm only interested in a "normal" letter?
use regex:
a.match(/[A-Za-z]/);
Use regex.
var a = " $#714 Abcd";
answer = a.match(/[A-Za-z]/)[0]
console.log(answer); // 'A'
You can use regex in order to match this expression:
a.match(/^[A-Za-z][A-Za-z0-9]*$/)
This will check whether the first character is alphabet and then the rest to be alphanumeric
This function will return an array with the positions in the string of all the first occurrence of any letter:
var s = 'asdlkn akn dlkandl nl ndvds';
function getFirstOccurrenceOffset(s) {
s = s.split("").reverse().join(""); // reverse the string
var re = /([A-Z])(?!.*\1)/gi;
var m;
var result = Array();
while ((m = re.exec(s)) !== null)
result.push(s.length - m.index - 1);
return result.reverse();
}
console.log(getFirstOccurrenceOffset(s));
The function is case insensitive, but you can remove the i modifier to make it case sensitive.
Related
I'm working on a drag and drop function for SVG path, which lets a user move the co-ordinates of the path.
Please consider the string below:
M162.323 150.513L232.645 8L303.504 149.837L461.168 173.5L347.156 284.5L373.605 440.728L233.5 367.854L91.7415 442L118.424 284.883L5.151 173.549Z
Would it be possible to replace a specific(let's say the 4th) occurence of a matched regex group using the .replace method?
Regex:
[A-Z](-?\d*\.?\d*\s-?\d*\.?\d*)
regex.exec() is a method that is used to find the next match in a string based on a regular expression. It returns an array containing the matched string and any capturing groups, or null if no match is found. This method can be used in a loop to iterate over all matches in a string and adjust the match accordingly.
let string = "M162.323 150.513L232.645 8L303.504 149.837L461.168 173.5L347.156 284.5L373.605 440.728L233.5 367.854L91.7415 442L118.424 284.883L5.151 173.549Z";
let regex = /[A-Z](-?\d*\.?\d*\s-?\d*\.?\d*)/g;
// Replace the 4th match
let newString = "";
let index = 0;
let match;
while (match = regex.exec(string)) {
if (index === 3) {
// Do something to modify the 4th match
newString += match[0].replace(/-?\d*\.?\d*\s-?\d*\.?\d*/, "REPLACED");
} else {
// Leave other matches unchanged
newString += match[0];
}
index++;
}
console.log(newString);
const s = 'M162.323 150.513L232.645 8L303.504 149.837L461.168 173.5L347.156 284.5L373.605 440.728L233.5 367.854L91.7415 442L118.424 284.883L5.151 173.549Z'
let n = 4, regex = /[A-Z](-?\d*\.?\d*\s-?\d*\.?\d*)/gm
console.log(s.replace(regex, m => --n ? m : 'hello'))
So I have this (example) string: 1234VAR239582358X
And I want to get what's in between VAR and X. I can easily replace it using .replace(/VAR.*X/, "replacement");
But, how would I get the /VAR.*X/as a variable?
I think what you are looking for might be
string.match(/VAR(.*)X/)[1]
The brackets around the .* mark a group. Those groups are returned inside the Array that match creates :)
If you want to only replace what's in between "VAR" and "X" it would be
string.replace(/VAR(.*)X/, "VAR" + "replacement" + "X");
Or more generic:
string.replace(/(VAR).*(X)/, "$1replacement$2");
You can try use the RegExp class, new RegExp(`${VAR}.*X`)
You can store it as variable like this,
const pattern = "VAR.*X";
const reg = new RegExp(pattern);
Then use,
.replace(reg, "replacement");
If you
want to get what's in between VAR and X
then using .* would do the job for the given example string.
But note that is will match until the end of the string, and then backtrack to the first occurrence of X it can match, being the last occurrence of the X char in the string and possible match too much.
If you want to match only the digits, you can match 1+ digits in a capture group using VAR(\d+)X
const regex = /VAR(\d+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);
if (m) {
let myVariable = m[1];
console.log(myVariable);
}
Or you can match until the first occurrence of an X char using a negated character class VAR([^\r\nX]+)X
const regex = /VAR([^\r\nX]+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);
if (m) {
let myVariable = m[1];
console.log(myVariable);
}
I'm working with a string where I need to extract the first n characters up to where numbers begin. What would be the best way to do this as sometimes the string starts with a number: 7EUSA8889er898 I would need to extract 7EUSA But other string examples would be SWFX74849948, I would need to extract SWFX from that string.
Not sure how to do this with regex my limited knowledge is blocking me at this point:
^(\w{4}) that just gets me the first four characters but I don't really have a stopping point as sometimes the string could be somelongstring292894830982 which would require me to get somelongstring
Using \w will match a word character which includes characters and digits and an underscore.
You could match an optional digit [0-9]? from the start of the string ^and then match 1+ times A-Za-z
^[0-9]?[A-Za-z]+
Regex demo
const regex = /^[0-9]?[A-Za-z]+/;
[
"7EUSA8889er898",
"somelongstring292894830982",
"SWFX74849948"
].forEach(s => console.log(s.match(regex)[0]));
Can use this regex code:
(^\d+?[a-zA-Z]+)|(^\d+|[a-zA-Z]+)
I try with exmaple and good worked:
1- somelongstring292894830982 -> somelongstring
2- 7sdfsdf5456 -> 7sdfsdf
3- 875werwer54556 -> 875werwer
If you want to create function where the RegExp is parametrized by n parameter, this would be
function getStr(str,n) {
var pattern = "\\d?\\w{0,"+n+"}";
var reg = new RegExp(pattern);
var result = reg.exec(str);
if(result[0]) return result[0].substr(0,n);
}
There are answers to this but here is another way to do it.
var string1 = '7EUSA8889er898';
var string2 = 'SWFX74849948';
var Extract = function (args) {
var C = args.split(''); // Split string in array
var NI = []; // Store indexes of all numbers
// Loop through list -> if char is a number add its index
C.map(function (I) { return /^\d+$/.test(I) === true ? NI.push(C.indexOf(I)) : ''; });
// Get the items between the first and second occurence of a number
return C.slice(NI[0] === 0 ? NI[0] + 1 : 0, NI[1]).join('');
};
console.log(Extract(string1));
console.log(Extract(string2));
Output
EUSA
SWFX7
Since it's hard to tell what you are trying to match, I'd go with a general regex
^\d?\D+(?=\d)
I get a string like:
str = “Test/hello/filename/12345678/first
Hddhkhd
Hdhal
filename/1212abcd/second”
I want to get an array of the all strings that comes after “filename//“ and I know that after the “/“ there is an 8 letter word that I want to get.
In this case, I want to get an array that will be:
strArr = [“12345678”, “1212abcd”]
How do I solve this problem?
A regex that captures the 8 characters that immediately follow a literal "filename//":
/filename\/\/(.{8})/
Try use this regex first:
filename\/\w{8}
and after it, slice from the result by this regex:
\w{8}$
First you will get:
filename/12345678
filename/1212abcd
Second you will get :
12345678
1212abcd
You might also capture in a group matching 8 times not a forward slash or a newline after matching /filename
\bfilename\/([^\/\n]{8})
Regex demo
If you want to match 8 or more times you could use {8,} instead or if you want to match 1 or more times you could use a +.
If you don't want to match whitespace characters you could change the \n to \s
const regex = /filename\/([^\/\n]{8})/g;
const str = `Test/hello/filename/12345678/first
Hddhkhd
Hdhal
filename/1212abcd/second`;
let m;
while ((m = regex.exec(str)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
console.log(m[1]);
}
You can use the following code. It will match all characters after the filename/ until it encounters another /. After you get the matches in an array you can map it out and replace all the filename/ with '':
let a = /filename\/[^\/]+/g;
let b = 'Test/hello/filename/12345678/first Hddhkhd Hdhal filename/1212abcd/second';
let c = b.match(a).map(x=>x.replace('filename/',''));
console.log(c);
For explanation check this REGEX
var arr = "Test/hello/filename/12345678/first Hddhkhd Hdhal filename/1212abcd/second".match(/(?<=filename\/)(.*?)(?=\/)/g);
console.log(arr)
OR
For unsupported Lookbehinds browser use Array#map after regex
var arr = "Test/hello/filename/12345678/first Hddhkhd Hdhal filename/1212abcd/second".match(/filename\/(.*?)\//g).map(i=> i.split('/')[1]);
console.log(arr)
I'm writing a function but cannot figure out how to account for upper case letter and punctuation.
My function is :
function countWords(word, string) {
var subStr = string.split(word);
return subStr.length - 1;
}
And it works when I try to test is with wordCount("hey","this is code hey"), but not if I try ("HEY", "this is code hey")
I tried
var subStr= string.toUpperCase().split(word)
but it will not work with lower case letters anymore.
Why can't you try like this.
function countWords(word, string) {
word= word.toLowerCase();
string=string.toLowerCase();
var subStr = string.split(word);
return subStr.length - 1;
}
So that whatever values we sent it will be converted into lower case then it will split.
Does it makes sense right?
Try this :
function countWords(word, string) {
var subStr = string.toLowerCase().split(word.toLowerCase());
return subStr.length - 1;
}
$(document).ready(function(){
$('#result').html(countWords("HEY","this is code hey"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="result"></div>
Try sending the parameter to either all upper or lower cases first so that it matches the case of the string you are comparing it to. For example,
function countWords(word.toLowerCase, string.toLowerCase)
That way the search is evaluated regardless of case.
You could use a regex with the i and g modifier (case insensitive/match all) and match, then return the length:
function wordCount(search, txt) {
var regex = new RegExp("\\W" + search + "\\W|\\W" + search, "ig");
var match = txt.match(regex);
return match ? match.length : 0;
}
console.log(wordCount("hey","this is code heyHey HEY hey")); // 2
If you want to have heyHey as 2 matches, simply remove |\\W" + search from the regex