Regext to match any substring longer than 2 characters - javascript

regex-pattern-to-match-any-substring-matching exact characters longer-than-two-characters-from-a-provided input,where ever exact string matches
Only pot or potato should be highlighted, instead of ota or ot, when user type pota and click search button.
Please find code below where matched string is highlighted.
// Core function
function buildRegexFor(find) {
var regexStr = find.substr(0,3);
for (var i = 1; i < find.length - 2; i++) {
regexStr = '(' + regexStr + find.substr(i+2,1) + '?|' + find.substr(i,3) + ')';
}
return regexStr;
}
// Handle button click event
document.querySelector('button').onclick = function () {
// (1) read input
var find = document.querySelector('input').value;
var str = document.querySelector('textarea').value;
// (2) build regular expression using above function
var regexStr = buildRegexFor(find);
// (3) apply regular expression to text and highlight all found instances
str = str.replace(new RegExp(regexStr, 'g'), "<strong class='boldtxt'>$1</strong>");
// (4) output
document.querySelector('span').textContent = regexStr;
document.querySelector('div').innerHTML = str;
};
consider "meter & parameter" as one string, if type meter in input box and click search button. meter should be highlighted as well as meter in parameter should highlight.Thanks in advance

Your for loop is set to go from i = 1, while i is less than find.length-2. find.length is 4. 4-2 is 2. So your for loop is set to go from i = 1 while i is less than 2. In other words, it's operating exactly once. I have no idea what you thought that for loop was going to do, but I'm betting that isn't it.
Prior to the for loop, regextr is set equal to the string pot (the first three characters of the find string. The first (and only) time through the for loop, it is set to a new value: the left paren, the existing value (pot), the fourth character of find (a), the question mark, the vertical bar, and three characters from find starting with the second. Put those together, and your regextr comes out to:
(pota?|ota)
That RegEx says to find either the string "pota" (with the a being optional, so "pot" also works) or the string "ota". So any instances of pota, pot, or ota will be found and highlighted.
If you just wanted "pota?", just eliminate the right half of that line inside the for loop. Better yet, replace the entire subroutine with just a line that appends the ? character to the find string.

Related

JavaScript: Replace certain occurrence of string depending on selection index

I've created my own autocomplete feature and I've come across a bug I'd like to fix. Here's an example of an incomplete sentence I might want to autocomplete the final word for:
let text = 'Hello there, I am her'
In my functionality the user clicks ctrl + enter and it autcompletes the word with a suggestion displayed on the page. In this case let's say the suggestion is 'here'. Also my controller knows where the user is based on the insertion cursor (so I have the index).
If I use replace like so:
text.replace(word, suggestion);
(Where word is 'her' and suggestion is 'here') it will replace the first occurrence. Obviously there are endless combinations of where this word might be in the text, how do I replace one at a certain index in text string? I know I can do it through some messy if conditions, but is there an elegant way to do this?
(If it is relevant I am using angular keydown/keyup for this)
EDIT>>>>>
This is not a duplicate on the question linked as in that case they are always replacing the last occurrence. If I did that then my program wouldn't support a user going back in their sentence and attempting to autocomplete a new word there
So, you have a position in a string and a number of characters to replace (=length of an incomplete word). In this case, would this work?
let text = 'appl and appl and appl'
function replaceAt(str, pos, len, replace) {
return str.slice(0, pos) + replace + str.slice(pos + len);
}
console.log(replaceAt(text, 0, 4, 'apple'))
console.log(replaceAt(text, 9, 4, 'apple'))
Gonna point you in a direction that should get you started.
let sentence = 'Hello lets replace all words like hello with Hi';
let fragments = sentence.split(' ');
for (let i=0; i<fragments.length; i++){
if(fragments[i].toLowerCase() == 'hello')
fragments[i] = 'Hi'
}
let formattedsentence = fragments.join(' ');
console.log(formattedsentence); //"Hi lets replace all words like Hi with Hi"

Split a text and put some text between them

i have a Javascript code from an extension im creating and i need to split the word im selecting in like, half for each part...
for example this is my code that i use for every page i need
function child1_7Search(info,tab) {
chrome.tabs.create({
url: "www.blablabla.com/" + info.selectionText,
});
}
but i have to split the selected code in 2. For example, my selected code is 1854BIGGER000208, where the first four letters need to be split in half and put somewhere in the URL and the other twelve letters needs to be put in other place, but in the URL.
the page needs to look something like this
https://www.urbano.com.ar/urbano3/wbs/cespecifica/?shi_codigo=001854&cli_codigo=BIGGER000208
where in shi_codigo adds two zeros and put the first half, and in cli_codigo puts the rest of the code.
The selected code its always the same length!
you can try to concatenate parts like this..
// this is your original text / code that you get
var text = "1854BIGGER000208"
// here we `slice` or take first 4 chars from it
var pret = text.slice(0,4);
// here we are taking other half of the text
var post = text.slice(4);
// and here we just concatenate them into final url part
var final = "shi_codigo" + "00" + pret + "&cli_codigo=" + post
console.log( final );
I guess that you will want to concatenate the first part of the url also and for that you can also prepend it with + sign as we did with all parts of the code above..
Here's a simple solution using .substring() method:
var code = "1854BIGGER000208";
var shi = "00" + code.substring(0, 4);
var cli = code.substring(4);
var url = "https://www.urbano.com.ar/urbano3/wbs/cespecifica/?shi_codigo=" + shi + "&cli_codigo=" + cli;
console.log(url);
Note:
code.substring(0, 4) will extract the first four digits from the selection, returns 1854.
And code.substring(4) will extract the remaining characters in the selection and returns BIGGER000208.
Note the use of "" in "00" the two zeros are wrapped in a string
so they can be concatenated with the shi code, otherwise 00+1854 will
be evaluated as 1854.
Here are a number of string functions you can use in JavaScript.
https://www.w3schools.com/jsref/jsref_obj_string.asp
In particular, you may want to use the slice function. Syntax is as follows :
var l = info.selectionText.length() - 1;
var num = info.selectionText.slice(0,3);
var end = info.selectionText.slice(4, l);
Here, the properties being passed into the slice function are the start and stop points of where you would like to slice the string. As usual, the index starts at 0.
Solution using ES6 Sintax
let yourString = "yourstringthatneedstobesliced";
let initial = yourString.slice(0,4);
let post = yourString.slice(4);
let char = `shi_codigo=00${initial}&cli_codigo=${post}`;

Split a string based on a condition

I would like to split a spreadsheet cell reference (eg, A10, AB100, ABC5) to two string parts: column reference and row reference.
A10 => A and 10
AB100 => AB and 100 ...
Does anyone know how to do this by string functions?
var res = "AA123";
//Method 1
var arr = res.match(/[a-z]+|[^a-z]+/gi);
document.write(arr[0] + "<br>" + arr[1]);
//Method 2 (as deceze suggested)
var arr = res.match(/([^\d]+)(\d+)/);
document.write("<br>" + arr[1] + "<br>" + arr[2]);
//Note here [^\d] is the same as \D
This is easiest to do with a regular expression (regex). For example:
var ref = "AA100";
var matches = ref.match(/^([a-zA-Z]+)([1-9][0-9]*)$/);
if (matches) {
var column = matches[1];
var row = Number(matches[2]);
console.log(column); // "AA"
console.log(row); // 100
} else {
throw new Error('invalid ref "' + ref + '"');
}
The important part here is the regex literal, /^([a-zA-Z]+)([1-9][0-9]*)$/. I'll walk you through it.
^ anchors the regex to the start of the string. Otherwise you might match something like "123ABC456".
[a-zA-Z]+ matches one or more character from a-z or A-Z.
[1-9][0-9]* matches exactly one character from 1-9, and then zero or more characters from 0-9. This makes sure that the number you are matching never starts with zero (i.e. "A001" is not allowed).
$ anchors the regex to the end of the string, so that you don't match something like "ABC123DEF".
The parentheses around ([a-zA-Z]+) and ([1-9][0-9]*) "capture" the strings inside them, so that we can later find them using matches[1] and matches[2].
This example is strict about only matching valid cell references. If you trust the data you receive to always be valid then you can get away with a less strict regex, but it is good practice to always validate your data anyway in case your data source changes or you use the code somewhere else.
It is also up to you to decide what you want to do if you receive invalid data. In this example I make the script throw an error, but there might be better choices in your situation (e.g. prompt the user to enter another value).

function email and name changing

I am trying to make function on Google spreadsheet (JavaScript). My understanding of java script is very low but would like to know basics. any help would be appreciated.
I have information that has capital of last name and Name. but I want to make that capital of last name in the end of name and add gmail in the end. for example IJOSH make it JoshIgmail by using function
=Letter("IJOSH") -> "JoshIgmail" so start by moving capital (last name ) to the end, result in JoshI. Finally, add "gmail" in the end
function("letter"){
var letter;
return(etter+L+gmail)
}
You could get this rearrangement with a simple regular expression:
var _value = "IJOSH",
suffix = "gmail";
_value.replace( /^(.)(.*)$/, "$2$1" + suffix );
This results in "JOSH" being moved to the front, "I" being moved to the middle, and "gmail" being appended to the end of the string.
The pattern used is fairly straight-forward. The / and / indicate the beginning and end of the pattern. ^ and $ denote the front and back of the string, meaning we don't want to match on subsets, but on the entire string itself.
When we wrap something in ( and ) we create a capture class, allowing us to later reference it like $1 or $2 (depending on which capture class it was). In regex, . represents any character. We modify this in the second capture class with *, which means the previous pattern (. in this case) can be found 0 or more times.
do you mean something line:
function someTest() {
var str = "lJOSH";
var result = str.substr(1).toLowerCase() + str.substr(0, 1) + "gmail";
return result.charAt(0).toUpperCase() + result.slice(1);
}
console.log( someTest("lJOSH") ); //returns Joshlgmail
There are multiple ways, but heres that I would do:
//example call would be createEmail("IJOSH")
function createEmail(inputName) {
//String Assigned to a name variable
var name = inputName;
//Split it into individual letters as an array
var letters = name.split(""); //["I", "J", "O", "S", "H"];
//Treat it as a queue and remove first letter (assign it to a variable)
var fLetter = letters.shift();
//Push it to end of stack
letters.push(fLetter);
//Put them back together and the 'gmail' string to the end
var email = letters.join("") + "gmail"; //JOSHIgmail
return email;
}
This is a long typed way to do this, but a good way to learn about strings and arrays.
EDIT: Not the sexiest solution but hopefully easy to understand

replace js with square brackets

I'm hoping there is a better way to write this? Removing [] square brackets are a problem to me.
alert(CanvasData)//images[]=Base.jpg&images[]=Frame_Clear.png&images[]=Left_Clear.png&images[]=Right_Clear.png&images[]=Lenses_Lenses-Semi-Clear.png&images[]=
var PayName = CanvasData.replace("images[]=", "");
PayName = PayName.replace(/\[.*?\]/g, '');
PayName = PayName.replace(/\&images=/g, ' ');
PayName = PayName.replace(/\.png/g, " &");
PayName = PayName.replace(/\_/g, ' ');
PayName = PayName.substring(8);//remove fist 8 character (Base.jpg)
PayName = PayName.substring(0, PayName.length - 2);//remove last 2 characters // Frame Clear & Left Clear & Right Clear & Lenses Lenses-Semi-Clear &
alert(PayName)// Frame Clear & Left Clear & Right Clear & Lenses Lenses-Semi-Clear
Thanks
Call replace with three global regular expressions, where the first call lists every alternate that should be replaced with nothing (i.e. remove all '=', and 'Base.jpg&'), the second lists alternates that should be replaced with a space ('images[]', '_', and '.png'), and the third ties up your loose ends:
var PayName = CanvasData.replace(/=|Base\.jpg&/g,'')
.replace(/images\[\]|_|\.png/g, ' ')
.replace(/^\s*|\s*&\s*$/g, '');
// => "Frame Clear & Left Clear & Right Clear & Lenses Lenses-Semi-Clear"
try escaping the brackets, otherwise they take on a special meaning (define a character class) for the regular expression.
CanvasData.replace("images\[\]=", "");
You are already doing the same thing, by the way, in the second line of code in the replace section.
If the square brackets [] are always empty, you could do:
var Payname = CanvasData.split("[]").join("");
Obviously that doesn't handle the general case.
What this does, is treat [] as a data separator, and turn the string into a parsed array -- just like parsing "1,3,6,4.5,3" except our comma is a []. Then the array formed by breaking up the string is joined back to a string, with a blank separator. All the [] disappear. But those [occupied] do not.

Categories

Resources