Putting together regex to highlight words inside a textbox [duplicate] - javascript

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 3 years ago.
Hey all I am trying to have a simple way of adding multiple item names to a regex list:
var whatToLookFor = "DOZ,DOB".split(",");
var highlightThis = "";
$.each(whatToLookFor,function(i){
highlightThis += whatToLookFor[i] + "\/|";
});
highlightThis = "\/" + highlightThis.replace(/.$/,"\/gi");
console.log(highlightThis);
/DOZ\/|DOB\//gi <-highlightThis should look like this
$('.string-example').highlightWithinTextarea({
highlight: highlightThis
});
However, I am not getting the same values shown on the page using highlightThis as I do when using the /DOZ/|DOB//gi. I output the value of highlightThis and it looks just like it should but still does not work for some reason.
$('.string-example').highlightWithinTextarea({
highlight: /DOZ\/|DOB\//gi
});
What could I be missing in order for it to treat it like a regex value? It's probably something simple that I am just overlooking. :o)
The code I am using is here
final working code
var whatToLookFor = "DOZ,DOB".split(",");
var highlightThis = "";
$.each(whatToLookFor,function(i){
highlightThis += whatToLookFor[i] + "/|";
});
highlightThis = highlightThis.replace(/.$/,"");
$('.string-example').highlightWithinTextarea({
highlight: new RegExp(highlightThis, 'gi')
});

The difference is you're creating it as a string vs as a regex. Instead of adding on gi at the end, use new RegExp and pass your string in and then your flags:
new RegExp('DOZ\\/|DOB/', 'gi');
This will output what you're expecting:
/DOZ\/|DOB//gi

Related

Javascript match and test returning null to DOI Regex expression [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 4 years ago.
I have been trying to find a way to recognize DOI on an input form to trigger a specific search.
I found a DOI regular expression here and when I use it with Match or Test I got 'NULL' and Error as result
function checkDOI(string){
//Redundant. I know
var testKey = String(string);
var DOIpattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])\S)+)\b';
var found = DOIpattern.test(testKey);
console.log("found", found + " DOI "+ testKey);
return found
}
checkDOI("10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7")
I got this error DOIpattern.test is not a function
Then if I change the found.test for MATCH var found = DOIpattern.match(testKey);
The result is NULL
Does anybody can tell me what I am doing wrong?
Thank in advance!
test is a method of RegExp class and not of String. To correct, create a RegExp object using the constructor and call the test method on it.
function checkDOI(string) {
//Redundant. I know
var testKey = String(string);
var DOIpattern = '\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>])\S)+)\b';
var found = new RegExp(DOIpattern).test(testKey);
console.log("found", found + " DOI " + testKey);
return found
}
checkDOI("10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7")
As long as your RegExp string is correct, the input should match.
create a RegExp object using the constructor and call the test method on it.
Thank you! your response worked. Just in case someone else is looking for a regular expression the one I am using is not properly written, so I cut it to this
\b(10[.][0-9]{4,}(?:[.][0-9]+)*\b/g
And the final version looks like this:
checkDOI(string){
var DOIpattern = new RegExp(/\b(10[.][0-9]{4,}(?:[.][0-9]+)*)\b/g);
// var DOIpattern = ;
var found = DOIpattern.test(testKey);
console.log("found", found + " DOI "+ testKey);
return found
}

Split text with {{Text}} format Javascript [duplicate]

This question already has answers here:
Regex to get string between curly braces
(16 answers)
Closed 4 years ago.
Sorry to bother you all. I'm no idea about regular expression. But right now I need one very badly.
I want to split text using this format {{Text}}. The "Text" can be anything. All I need is split the text at the position of {{Text}}.
Here is a sample.
var Regx = My Regx;
var String = "{{This}} is a {{test}} string to be {{spliced}} with {{Regular}} Expression";
var SplitArray = String.split(Regx);
// it will give me an array like this
// ["","is a ","string to be "," with"," Expression"]
Thank you in advance.
Edit:
I solved it myself too. It is {{[^{}]+}}
You can do this way
var test = "{{This}} is a {{test}} string to be {{spliced}} with {{Regular}} Expression";
var SplitArray = test.split(/\{\{.*?\}\}/);
console.log(SplitArray)
Try this:
var Regx = /\{\{.*?\}\}/;
var String = "{{This}} is a {{test}} string to be {{spliced}} with {{Regular}} Expression";
var SplitArray = String.split(Regx);
console.log(SplitArray);
// it will give me an array like this
// ["","is a ","string to be "," with"," Expression"]

Javascript RegExp: How to remove all charcters after // until a new line [duplicate]

This question already has answers here:
RegEx for match/replacing JavaScript comments (both multiline and inline)
(17 answers)
Closed 5 years ago.
Basically what I want to do is parse code, and remove all comments made with "//", including the "//", until a new line appears. I don't know how to effectivly do it in Regex unfortunately.
Some example code might look like this:
variable += 10; //comment to be removed.
more code...
so only "//comment to be removed." gets removed
console.log(`something // awodkajwodkjoawjdojawdjk
another thing // fgskgkjhgkf
last thing`.replace(/\/\/.*/g, ''));
This will allow you to parse the code, instead of just removing the comments from a string:
var code = getCode();
var stripped = '';
var regex = /(.*)\/\/.*/g;
var result;
while ( result = regex.exec( code ) ) {
console.log( result );
// Do other stuff with line of code
stripped += ( result[1] + '\n' );
}

pass variable to replace function regular expression javascript [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 6 years ago.
I want to have a 'newline'-function to pass a string to it and print it on pdf. my function so far is
var array = new Array();
function newLineFunction_PDF(text) {
var arr = text.replace(/.{70}\S*\s+/g, "$&#").split(/\s+#/);
return arr;
}
array = newLineFunction_PDF('some Text');
for( var i in array) {
print(array[i]);
}
What it does is cut the text in to pieces of length-70 incl. the last word, push it into the array and print it afterwards with new lines. Now i want to pass a number to the function, like 100, so i can decide the max-length of the text per line.
So far I tried:
function newLineFunction_PDF(text, num) {
var re = new RegExp(/.{num}\S*\s+/g);
var arr = text.replace(re, "$&#").split(/\s+#/);
return arr;
}
but I dont know how and where to add escapes into the new RegExp.
The parameter of Regexp is a string:
var re = new RegExp('.{' + num + '}\S*\s+', 'g');

How to trim a string to its last four characters? [duplicate]

This question already has answers here:
How to get the last character of a string?
(15 answers)
Closed 8 years ago.
I know there are methods to remove characters from the beginning and from the end of a string in Javascript. What I need is trim a string in such a way that only the last 4 characters remain.
For eg:
ELEPHANT -> HANT
1234567 -> 4567
String.prototype.slice will work
var str = "ELEPHANT";
console.log(str.slice(-4));
//=> HANT
For, numbers, you will have to convert to strings first
var str = (1234567).toString();
console.log(str.slice(-4));
//=> 4567
FYI .slice returns a new string, so if you want to update the value of str, you would have to
str = str.slice(-4);
Use substr method of javascript:
var str="Elephant";
var n=str.substr(-4);
alert(n);
You can use slice to do this
string.slice(start,end)
lets assume you use jQuery + javascript as well.
Lets have a label in the HTML page with id="lblTest".
<script type="text/javascript">
function myFunc() {
val lblTest = $("[id*=lblTest]");
if (lblTest) {
var str = lblTest.text();
// this is your needed functionality
alert(str.substring(str.length-4, str.length));
} else {
alert('does not exist');
}
}
</script>
Edit: so the core part is -
var str = "myString";
var output = str.substring(str.length-4, str.length);

Categories