I have a string "#{Name; 11112121#xyz.com}"
I want to write a regular expression that extracts Name and 11112121 from the above string
This is what I tried.
function formatName(text){
var regex = /#\{([^;]+); ([^\}]+)\}/
return text.replace(
regex,
'$1, $2'
);
}
The above gives Name, 11112121#xyz.com. But I want only Name, 11112121
try this
var regex = /#\{([^;]+); ([^\}]+)(#.*)\}/
$1 => Name
$2=> 11112121
Here is the working example
Use match instead, like this:
var regex = /#\{([^;]+);\s+([^#]+)/;
var matches = text.match(regex);
alert(matches[1] + ', ' + matches[2]);
http://jsfiddle.net/rooseve/bM2U6/
If you want to match everything until the # character, you can use
var regex = /#\{([^;]+); ([^#]+)/
If you need to verify that the string also contains a } after that, you can add that to the end:
var regex = /#\{([^;]+); ([^#]+)[^}]*\}/
Related
I have a long string
Full_str1 = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;';
removable_str2 = 'ab#xyz.com;';
I need to have a replaced string which will have
resultant Final string should look like,
cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;
I tried with
str3 = Full_str1.replace(new RegExp('(^|\\b)' +removable_str2, 'g'),"");
but it resulted in
cab#xyz.com;c-c.c_ab#xyz.com;
Here a soluce using two separated regex for each case :
the str to remove is at the start of the string
the str to remove is inside or at the end of the string
PS :
I couldn't perform it in one regex, because it would remove an extra ; in case of matching the string to remove inside of the global string.
const originalStr = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;ab#xyz.com;c_ab#xyz.com;';
const toRemove = 'ab#xyz.com;';
const epuredStr = originalStr
.replace(new RegExp(`^${toRemove}`, 'g'), '')
.replace(new RegExp(`;${toRemove}`, 'g'), ';');
console.log(epuredStr);
First, the dynamic part must be escaped, else, . will match any char but a line break char, and will match ab#xyz§com;, too.
Next, you need to match this only at the start of the string or after ;. So, you may use
var Full_str1 = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;';
var removable_str2 = 'ab#xyz.com;';
var rx = new RegExp("(^|;)" + removable_str2.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "g");
console.log(Full_str1.replace(rx, "$1"));
// => cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;
Replace "g" with "gi" for case insensitive matching.
See the regex demo. Note that (^|;) matches and captures into Group 1 start of string location (empty string) or ; and $1 in the replacement pattern restores this char in the result.
NOTE: If the pattern is known beforehand and you only want to handle ab#xyz.com; pattern, use a regex literal without escaping, Full_str1.replace(/(^|;)ab#xyz\.com;/g, "$1").
i don't find any particular description why you haven't tried like this it will give you desired result cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;
const full_str1 = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;';
const removable_str2 = 'ab#xyz.com;';
const result= full_str1.replace(removable_str2 , "");
console.log(result);
I have some string that looks like this:
var string = popupLink(25, 'Any string')
I need to use a regular expression to change the number inside (note that this is a string inside of a larger string so I can't simply match and replace the number, it needs to match the full pattern, this is what I have so far:
var re = new RegExp(`popupLink\(${replace},\)`, 'g');
var replacement = `popupLink(${formFieldInsert.insertId},)`;
string = string.replace(re, replacement);
I can't figure out how to do the wildcard that will maintain the 'Any String' part inside of the Regular Expression.
If you are looking for a number, you should use \d. This will match all numbers.
For any string, you can use lazy searching (.*?), this will match any character until the next character is found.
In your replacement, you can use $1 to use the value of the first group between ( and ), so you don't lose the 'any string' value.
Now, you can simply do the following:
var newNumber = 15;
var newString = "var string = popupLink(25, 'Any string')".replace(/popupLink\(\d+, '(.*?)'\)/, "popupLink(" + newNumber + ", '$1')");
console.log(newString);
If you just need to change the number, just change the number:
string = string.replace(/popupLink\(\d+/, "popupLink(" + replacement);
Example:
var str = "var string = popupLink(25, 'Any string')";
var replacement = 42;
str = str.replace(/popupLink\(\d+/, "popupLink(" + replacement);
console.log(str);
If you really do have to match the full pattern, and "Any String" can literally be any string, it's much, much more work because you have to allow for quoted quotes, ) within quotes, etc. I don't think just a single JavaScript regex can do it, because of the nesting.
If we could assume no ) within the "Any String", then it's easy; we just look for a span of any character other than ) after the number:
str = str.replace(/(popupLink\()\d+([^)]*\))/, "$1" + replacement + "$2");
Example:
var str = "var string = popupLink(25, 'Any string')";
var replacement = 42;
str = str.replace(/(popupLink\()\d+([^)]*\))/, "$1" + replacement + "$2");
console.log(str);
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']
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
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))