JavaScript regular expression to match hyphenated words? - javascript

I'd like a JavaScript regular expression that can match a string either at the start of another string, or after a hyphen in the string.
For example, "milne" and "lee" and "lees" should all match "Lees-Milne".
This is my code so far:
var name = "Lees-Milne";
var text = "lee";
// I don't know what 'text' is ahead of time, so
// best to use RegExp constructor.
var re = RegExp("^" + text | "-" + text, "i");
alert(re.exec(name.toLowerCase()));
However, this returns null. What am I doing wrong?

You could also use:
var re = RegExp("(?:^|-)" + text, "i");
Don't forget to escape regex meta characters in text if it's not an expression it self.
JavaScript has no built in function for that, but you could use:
function quotemeta(str){
return str.replace(/[.+*?|\\^$(){}\[\]-]/g, '\\$&');
}

Related

Removing the backslash from a literal notation of a regex

I need to create a regex from user input string. This is my code. I have input with id 'regex'.
<input id='regex'/>
And this is my js code.
var regex = $('#regex').val();
regexp = new RegExp(regex);
testString = "foo is bar";
alert(testString.replace(regexp, ''));
But if I add / /g as an example to remove spaces from a string it's not working. And I get this as regexp
/\/ \/g/
is there a way to convert this to exactly like my string as regex?
If the user puts / on each side of the pattern, followed by word characters and the end of the string on the right, parse them out before passing to new RegExp, and pass the word characters as the second argument:
$('#regex').on('change', () => {
const input = $('#regex').val();
const match = input.match(/^\/(.*)\/(\w+)$/);
const pattern = match
? new RegExp(match[1], match[2])
: new RegExp(input);
console.log(pattern);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id='regex'/>

Regular Expression to match compound words using only the first word

I am trying to create a regular expression in JS which will match the occurences of box and return the full compound word
Using the string:
the box which is contained within a box-wrap has a box-button
I would like to get:
[box, box-wrap, box-button]
Is this possible to match these words only using the string box?
This is what I have tried so far but it does not return the results I desire.
http://jsfiddle.net/w860xdme/
var str ='the box which is contained within a box-wrap has a box-button';
var regex = new RegExp('([\w-]*box[\w-]*)', 'g');
document.getElementById('output').innerHTML=str.match(regex);
Try this way:
([\w-]*box[\w-]*)
Regex live here.
Requested by comments, here is a working example in javascript:
function my_search(word, sentence) {
var pattern = new RegExp("([\\w-]*" + word + "[\\w-]*)", "gi");
sentence.replace(pattern, function(match) {
document.write(match + "<br>"); // here you can do what do you want
return match;
});
};
var phrase = "the box which is contained within a box-wrap " +
"has a box-button. it is inbox...";
my_search("box", phrase);
Hope it helps.
I'll just throw this out there:
(box[\w-]*)+
You can use this regex in JS:
var w = "box"
var re = new RegExp("\\b" + w + "\\S*");
RegEx Demo
This should work, note the 'W' is upper case.
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
\Wbox\W
It looks like you're wanting to use the match with a regex. Match is a string method that will take a regex as an argument and return an array containing matches.
var str = "your string that contains all of the words you're looking for";
var regex = /you(\S)*(?=\s)/g;
var returnedArray = str.match(regex);
//console.log(returnedArray) returns ['you', 'you\'re']

Use dynamic (variable) string as regex pattern in JavaScript

I want to add a (variable) tag to values with regex, the pattern works fine with PHP but I have troubles implementing it into JavaScript.
The pattern is (value is the variable):
/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is
I escaped the backslashes:
var str = $("#div").html();
var regex = "/(?!(?:[^<]+>|[^>]+<\\/a>))\\b(" + value + ")\\b/is";
$("#div").html(str.replace(regex, "" + value + ""));
But this seem not to be right, I logged the pattern and its exactly what it should be.
Any ideas?
To create the regex from a string, you have to use JavaScript's RegExp object.
If you also want to match/replace more than one time, then you must add the g (global match) flag. Here's an example:
var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
In the general case, escape the string before using as regex:
Not every string is a valid regex, though: there are some speciall characters, like ( or [. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:
function escapeRegExp(stringToGoIntoTheRegex) {
return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
Note: the regex in the question uses the s modifier, which didn't exist at the time of the question, but does exist -- a s (dotall) flag/modifier in JavaScript -- today.
If you are trying to use a variable value in the expression, you must use the RegExp "constructor".
var regex = "(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b";
new RegExp(regex, "is")
I found I had to double slash the \b to get it working. For example to remove "1x" words from a string using a variable, I needed to use:
str = "1x";
var regex = new RegExp("\\b"+str+"\\b","g"); // same as inv.replace(/\b1x\b/g, "")
inv=inv.replace(regex, "");
You don't need the " to define a regular expression so just:
var regex = /(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is; // this is valid syntax
If value is a variable and you want a dynamic regular expression then you can't use this notation; use the alternative notation.
String.replace also accepts strings as input, so you can do "fox".replace("fox", "bear");
Alternative:
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(.*?)\b/", "is");
Keep in mind that if value contains regular expressions characters like (, [ and ? you will need to escape them.
I found this thread useful - so I thought I would add the answer to my own problem.
I wanted to edit a database configuration file (datastax cassandra) from a node application in javascript and for one of the settings in the file I needed to match on a string and then replace the line following it.
This was my solution.
dse_cassandra_yaml='/etc/dse/cassandra/cassandra.yaml'
// a) find the searchString and grab all text on the following line to it
// b) replace all next line text with a newString supplied to function
// note - leaves searchString text untouched
function replaceStringNextLine(file, searchString, newString) {
fs.readFile(file, 'utf-8', function(err, data){
if (err) throw err;
// need to use double escape '\\' when putting regex in strings !
var re = "\\s+(\\-\\s(.*)?)(?:\\s|$)";
var myRegExp = new RegExp(searchString + re, "g");
var match = myRegExp.exec(data);
var replaceThis = match[1];
var writeString = data.replace(replaceThis, newString);
fs.writeFile(file, writeString, 'utf-8', function (err) {
if (err) throw err;
console.log(file + ' updated');
});
});
}
searchString = "data_file_directories:"
newString = "- /mnt/cassandra/data"
replaceStringNextLine(dse_cassandra_yaml, searchString, newString );
After running, it will change the existing data directory setting to the new one:
config file before:
data_file_directories:
- /var/lib/cassandra/data
config file after:
data_file_directories:
- /mnt/cassandra/data
Much easier way: use template literals.
var variable = 'foo'
var expression = `.*${variable}.*`
var re = new RegExp(expression, 'g')
re.test('fdjklsffoodjkslfd') // true
re.test('fdjklsfdjkslfd') // false
Using string variable(s) content as part of a more complex composed regex expression (es6|ts)
This example will replace all urls using my-domain.com to my-other-domain (both are variables).
You can do dynamic regexs by combining string values and other regex expressions within a raw string template. Using String.raw will prevent javascript from escaping any character within your string values.
// Strings with some data
const domainStr = 'my-domain.com'
const newDomain = 'my-other-domain.com'
// Make sure your string is regex friendly
// This will replace dots for '\'.
const regexUrl = /\./gm;
const substr = `\\\.`;
const domain = domainStr.replace(regexUrl, substr);
// domain is a regex friendly string: 'my-domain\.com'
console.log('Regex expresion for domain', domain)
// HERE!!! You can 'assemble a complex regex using string pieces.
const re = new RegExp( String.raw `([\'|\"]https:\/\/)(${domain})(\S+[\'|\"])`, 'gm');
// now I'll use the regex expression groups to replace the domain
const domainSubst = `$1${newDomain}$3`;
// const page contains all the html text
const result = page.replace(re, domainSubst);
note: Don't forget to use regex101.com to create, test and export REGEX code.
var string = "Hi welcome to stack overflow"
var toSearch = "stack"
//case insensitive search
var result = string.search(new RegExp(toSearch, "i")) > 0 ? 'Matched' : 'notMatched'
https://jsfiddle.net/9f0mb6Lz/
Hope this helps

Regex Wildcard for Array Search

I have a json array that I currently search through by flipping a boolean flag:
for (var c=0; c<json.archives.length; c++) {
if ((json.archives[c].archive_num.toLowerCase().indexOf(query)>-1)){
inSearch = true;
} }
And I have been trying to create a wildcard regex search by using a special character '*' but I haven't been able to loop through the array with my wildcard.
So what I'm trying to accomplish is when query = '199*', replace the '*' with /[\w]/ and essentially search for 1990,1991,1992,1993,1994 + ... + 199a,199b, etc.
All my attempts turn literal and I end up searching '199/[\w]/'.
Any ideas on how to create a regex wildcard to search an array?
Thanks!
You should write something like this:
var query = '199*';
var queryPattern = query.replace(/\*/g, '\\w');
var queryRegex = new RegExp(queryPattern, 'i');
Next, to check each word:
if(json.archives[c].archive_num.match(queryRegex))
Notes:
Consider using ? instead of *, * usually stands for many letters, not one.
Note that we have to escape the backslash so it will create a valid string literal. The string '\w' is the same as the string w - the escape is ignored in this case.
You don't need delimiters (/.../) when creating a RegExp object from a string.
[\w] is the same as \w. Yeah, minor one.
You can avoid partial matching by using the pattern:
var queryPattern = '\\b' query.replace(/\*/g, '\\w') + '\\b';
Or, similarly:
var queryPattern = '^' query.replace(/\*/g, '\\w') + '$';
var qre = query.replace(/[^\w\s]/g, "\\$&") // escape special chars so they dont mess up the regex
.replace("\\*", "\\w"); // replace the now escaped * with '\w'
qre = new RegExp(qre, "i"); // create a regex object from the built string
if(json.archives[c].archive_num.match(qre)){
//...
}

Replace a substring with javascript

Need to replace a substring in URL (technically just a string) with javascript.
The string like
http://blah-blah.com/search?par_one=test&par_two=anothertest&SearchableText=TO_REPLACE
or
http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest
means, the word to replace can be either at the most end of the URL or in the middle of it.
I am trying to cover these with the following:
var newWord = NEW_SEARCH_TERM;
var str = 'http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest';
var regex = /^\S+SearchableText=(.*)&?\S*$/;
str = str.replace(regex, newWord);
But no matter what I do I get str = NEW_SEARCH_TERM. Moreover the regular expression when I try it in RegExhibit, selects the word to replace and everything that follows it that is not what I want.
How can I write a universal expression to cover both cases and make the correct string be saved in the variable?
str.replace(/SearchableText=[^&]*/, 'SearchableText=' + newWord)
The \S+ and \S* in your regex match all non-whitespace characters.
You probably want to remove them and the anchors.
http://jsfiddle.net/mplungjan/ZGbsY/
ClyFish did it while I was fiddling
var url1="http://blah-blah.com/search?par_one=test&par_two=anothertest&SearchableText=TO_REPLACE";
var url2 ="http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest"
var newWord = "foo";
function replaceSearch(str,newWord) {
var regex = /SearchableText=[^&]*/;
return str.replace(regex, "SearchableText="+newWord);
}
document.write(replaceSearch(url1,newWord))
document.write('<hr>');
document.write(replaceSearch(url2,newWord))

Categories