JavaScript Regex Ignore Case - javascript

I am trying to match a part of the string and it should be NOT case sensitive. I have the following code but I never get the replaced string.
var name = 'Mohammad Azam'
var result = name.replace('/' + searchText + '/gi', "<b>" + searchText + "</b>");
The searchText variable will be "moha" or "mo" or "moh".
How can I get the matching thing in bold tags.

/pattern/ has meaning when it's put in as a literal, not if you construct string like that. (I am not 100% sure on that.)
Try
var name = 'Mohammad Azam';
var searchText = 'moha';
var result = name.replace(new RegExp('(' + searchText + ')', 'gi'), "<b>$1</b>");
//result is <b>Moha</b>mmad Azam
EDIT:
Added the demo page for the above code.
Demo →
Code

I think you're looking for new RegExp, which creates a dynamic regular expression - what you're trying to do now is match a string ( not a regexp object ) :
var name = 'Mohammad Azam', searchText='moha';
var result = name.replace(new RegExp(searchText, 'gi'), "" + searchText + ""); result
EDIT: Actually, this is probably what you were looking for, nevermind ^
var name = 'Mohammad Azam', searchText='moha';
name.match( new RegExp( searchText , 'gi' ) )[0]
name // "Moha"

Related

Emphasize the part of a word that is not given

I have the code:
var word = 'thisistheword';
var string = 'istheword';
console.log(word.replace(new RegExp(string, "gi"), "<b>"+string+"</b>"));
And now I get this<b>istheword</b>, but I want to receive inverted result, so: <b>this</b>istheword.
var word = 'thisistheword';
var string = 'istheword';
console.log(word.replace(new RegExp("(.*)" + string , "gi"), "<b>$1</b>" + string));
gives: <b>this</b>istheword
"(.*)" + string means match everything preceding string.
Wrapped in () so that you can refer to it later with the $1

Change data inside string with box brackets

I have a string
garments[0][1]; // The 0 and 1 can be other numbers
I need to replace the data inside the second and the third box brackets.
[0] and [1]
So that it can be
garments[4][6]
Please let me know your suggestions when you get a chance, thank you.
You can try that:
var string = 'garments[' + 4 + '][' + 6 + ']'; //in your onClick function
//To increment dynamically:
var string = 'garments[' + i + '][' + j + ']'; //i and j being variables incrementing in your loops/treatments
Update to address comments:
If you want to break "garnments[0][1]" into "garnments",0 and 1 you can do the following:
var string = "garnments[0][1]";
string = string.split('['); //string = [["garnments"],["0]"],["1]"]]
string[1].replace(']','');
string[2].replace(']',''); //string = [["garnments"],["0"],["1"]]
You can then change values and rebuild your string for further use.
It is a bit brutal though. You can use RegExp as showed by #Diego
You can use String.prototype.replace()
'garments[0][1]'.replace('[0]','[4]').replace('[1]','[6]')
For any possible string with ***[m][n] format:
Function SetNewValues(testString, n, m)
{
var keyWordLengh = testString.indexOf("[");
return testString.substring(0,keyWordLengh) + "[" + n.toString() + "][" + m.toString() + "]";
}
Where:
testString is entire string to work on, like "something[342][345]"
n,m are values to be put inside brackets :)
This would be my approach.
var string = "['foobar'][2][12]";
var match =
/\[([^\]]+)\](?:\[(\d+)\])(?:\[(\d+)\])/g
.exec(string);
console.log(match);

get particular strings from a text that separated by underscore

I am trying to get the particular strings from the text below :
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
From this i have to get the following strings: "LAST", "BRANCH" and "JENKIN".
I used the code below to get "JENKIN";
var result = str.substr(str.lastIndexOf("_") +1);
It will get the result "JENKIN.bin". I need only "JENKIN".
Also the input string str sometimes contains this ".bin" string.
with substring() function you can extract text you need with defining start and end position. You have already found the start position with str.lastIndexOf("_") +1 and adding end position with str.indexOf(".") to substring() function will give you the result you need.
var result = str.substring(str.lastIndexOf("_") +1,str.indexOf("."));
It depends on how predictable the pattern is. How about:
var parts = str.replace(/\..+/, '').split('_');
And then parts[0] is 001AN, parts[1] is LAST, etc
You can use String.prototype.split to split a string into an array by a given separator:
var str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin';
var parts = str.split('_');
// parts is ['001AN', 'LAST', 'BRANCH', 'HYB', '1hhhhh5', 'PBTsd', 'JENKIN.bin'];
document.body.innerText = parts[1] + ", " + parts[2] + " and " + parts[6].split('.')[0];
You could do that way:
var re = /^[^_]*_([^_]*)_([^_]*)_.*_([^.]*)\..*$/;
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var matches = re.exec(str);
console.log(matches[1]); // LAST
console.log(matches[2]); // BRANCH
console.log(matches[3]); // JENKIN
This way you can reuse your RegExp anytime you want, and it can be used in other languages too.
Try using String.prototype.match() with RegExp /([A-Z])+(?=_B|_H|\.)/g to match any number of uppercase letters followed by "_B" , "_H" or "."
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var res = str.match(/([A-Z])+(?=_B|_H|\.)/g);
console.log(res)
I don't know why you want to that, but this example would be helpful.
It will be better write what exactly you want.
str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin'
find = ['LAST', 'BRANCH', 'JENKINS']
found = []
for item in find:
if item in str:
found.append(item)
print found # ['LAST', 'BRANCH']

Replace string with a function of replaced string

I would like to find a performant and elegant solution to this problem :
I need to replace a substring of a string, case insensitively, by a function of what have been replaced.
Example :
var highlight = function(inputString, filterString) {
var regex = new RegExp(filterString, 'gi');
return inputString.replace(regex, '<b>' + filterString + '</b>');
};
highlight('The input', 't');
If your run this in your browser console, you'll get :
"<b>t</b>he inpu<b>t</b>"
My problem is that I'd like to keep the original case of the replaced string. Therefore, the expected result would be :
"<b>T</b>he inpu<b>t</b>"
Any idea ?
Edit: Answer by #georg:
return inputString.replace(regex, '<b>$&</b>');
Just use $& in the replacement, which means "what has been found":
var highlight = function(inputString, filterString) {
var regex = new RegExp(filterString, 'gi');
return inputString.replace(regex, '<b>$&</b>');
};
x = highlight('The input', 't');
document.write("<pre>" + JSON.stringify(x,0,3));
Other $... magic constructs, for the reference:
MDN
$& contains the string matched by the last pattern match.
Please refer
https://msdn.microsoft.com/en-us/library/ie/3k9c4a32%28v=vs.94%29.aspx
for more details.

javascript regex to replace a substring

In javascript, how would I use a regular expression to replace everything to the right of "Source="
Assume, for example:
var inStr="http://acme.com/mainpage.aspx?ID=25&Source=http://acme.com/fruitPage.aspx"
var newSoruceValue="http://acme.com/vegiePage.aspx"
Goal is to get this value in outStr:
var outStr="http://acme.com/mainpage.aspx?ID=25&Source=http://acme.com/vegiePage.aspx"
Thanks!!
Assumes that source= will always be at the end
var inStr="http://acme.com/mainpage.aspx?ID=25&Source=http://acme.com/fruitPage.aspx"
var newSourceValue="http://acme.com/vegiePage.aspx"
var outStr = inStr.replace( /(Source=).*/, "$1" + newSourceValue);
Is "Source" always linked to the first occurrance of "&"?
You could use
indexOf("&") + 7
(number of letters in the word "Source" + one for "=").
Then create the new string by appending the new source to the substring using the index from before.
string.replace( /pattern/, replace_text );
var outStr = inStr.replace( /&Source=.*$/, "&Source=" + newSoruceValue );
or
var outStr = inStr.replace( /(&Source=).*$/, "$1" + newSoruceValue )

Categories

Resources