Trying to get a filename and have it return a string.
try to turn:
plate-71-winter-hawk-final.jpg
into:
winter hawk final
where plate might also be uppercase. Here is what I have so far, doesn't seem to work
var theRegEx = new RegExp('[Plate|plate]-\d+-(.*).jpg');
var theString = "plate-71-winter-hawk-final.jpg"
var newString = theString.replace(theRegEx, theString);
newString;
Unfortunately, the "Rule #1" doesn't offer a better way:
var newString = theString.replace(/^[Pp]late-\d+-(.*)\.jpg$/, '$1')
.replace(/-/g, ' ');
Take care when you use a string with the object syntax to escape backslahes:
var theRegEx = new RegExp('^[Pp]late-\\d+-(.*)\\.jpg$');
Note that a character class is only a set of characters, you can't use it to put substrings and special regex characters loose their meaning inside it. [Plate|plate] is the same thing than [Pplate|]
You can write it like this too (without string):
var theRegEx = new RegExp(/^[Pp]late-\d+-(.*)\.jpg$/);
Try following script. It's not dependent on length of string as long as it follows standard pattern:
var data = "plate-71-winter-hawk-final.jpg";
var rx = /(?:plate\-\d+\-)(.*)(?=\.)/i;
var match = rx.exec(data);
if(match != null){
data = match[1];
data = data.replace(/\-/g, ' ');
}
console.log(data);
It will print:
winter hawk final
Related
I have a string look like:
var str = https://sharengay.com/movie13.m3u8?pid=144.21.112.0&tcp=none
I want to remove at start ?pid= to end. The result look like:
var str = https://sharengay.com/movie13.m3u8
I tried to:
str = str.replace(/^(?:?pid=)+/g, "");
But it show error like:
Invalid regular expression: /^(?:?pid=)+/: Nothing to repeat
If you really want to do this at the string level with regex, it's simply replacing /\?pid=.*$/ with "":
str = str.replace(/\?pid=.*$/, "");
That matches ?pid= and everything that follows it (.*) through the end of the string ($).
Live Example:
var str = "https://sharengay.com/movie13.m3u8?pid=144.21.112.0&tcp=none";
str = str.replace(/\?pid=.*$/, "");
console.log(str);
You can use split
var str = "https://sharengay.com/movie13.m3u8?pid=144.21.112.0&tcp=none"
var result = str.split("?pid=")[0];
console.log(result);
You can simply use split(), which i think is simple and easy.
var str = "https://sharengay.com/movie13.m3u8?pid=144.21.112.0&tcp=none";
str = str.split("?pid");
console.log(str[0]);
You may create a URL object and concatenate the origin and the pathname:
var str = "https://sharengay.com/movie13.m3u8?pid=144.21.112.0&tcp=none";
var url = new URL(str);
console.log(url.origin + url.pathname);
You have to escape the ? and if you want to remove everything from that point you also need a .+:
str = str.replace(/\?pid=.+$/, "")
You can use split function to get only url without query string.
Here is the example.
var str = 'https://sharengay.com/movie13.m3u8?pid=144.21.112.0&tcp=none';
var data = str.split("?");
alert(data[0]);
trying to find every match in a string and process it with a custom function and replace it in the string. When I set text = to the new string though, it never changes, and in the end remains the unchanged.
function submit () {
var searchTerm = document.querySelector('#search-term').value;
var replaceFunction = Function('input', document.querySelector('#function').value);
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
var output = text;
var regex = new RegExp('\d', 'g');
var match, matches = [];
//search for replacements
while ((match = regex.exec(text)) != null) {
var beforeMatch = output.substring(0, match.index);
var afterMatch = output.substring(match.index + match[0].length, text.length);
text = beforeMatch + replaceFunction(match[0]) + afterMatch;
console.log(text);
}
console.log('result', text);
}
function replaceFunction (input) {
return input * 2;
}
You can achieve same result with far less code using replace() and its function's callback that takes match as parameter.
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
text = text.replace(/\d+/g, function(match){
return parseInt(match) * 2;
})
console.log(text)
First of all, you need to use \\ for escape sequence if you are using RegExp constructor. Alternatively you can use the RegExp literal as shown below. Moreover you are using only \d which is going to match a single digit. Instead you should be using \d+ that will match the complete number.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
When using the constructor function, the normal string escape rules
(preceding special characters with \ when included in a string) are
necessary. For example, the following are equivalent:
var re = /\w+/;
var re = new RegExp('\\w+');
Then you are trying to manipulate the string using a loop. Instead simply use replace function as shown below.
function submit () {
// var searchTerm = document.querySelector('#search-term').value;
// var replaceFunction = Function('input', document.querySelector('#function').value);
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
var output = text;
var regex = new RegExp('\\d+', 'g'); // <<<<<< RegExp constructor
// OR
regex = /\d+/g; // <<<<<<< RegExp literal
var match, matches = [];
console.log(text);
output = text.replace(regex, replaceFunction);
console.log('result', output);
}
function replaceFunction (input) {
return parseInt(input) * 2;
}
submit();
Disclaimer: Using RegExp for manipulating HTML elements and attributes is not a good idea and you may end up in unexpected issues if its not used carefully. Use it at your own risk.
I want to get a portion of a string via .substring(indexStart, indexEnd) then replace the same portion in the original string.
var portion = "my new house".substring(3, 6),
portion = "old";
// what's next?
You could take the surrounding substrings and concatenate:
var str = "my new house";
str = str.slice(0, 3) + "old" + str.slice(6);
console.log(str); // "my old house"
Of course, this is assuming you want to replace parts of the string marked off by certain indeces. If you just want to replace a word, you would use:
str = str.replace(/new/g, 'old');
(Omit the global flag to only replace the first occurrence.)
You just need to call 'replace' on the original string to find the substring you gathered and replace it with the new desired string.
var oldString = "my new house my new house";
var subStr = oldString.substring(indexStart, indexEnd);
var newValue = "old";
var newString = oldString.replace(subStr, newValue);
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
I nee to replace all numbers after underline inside a string.
I think that I can use Regex, but I don't know how to use Regex Syntax
See an example of my string:
milton_0
milton_1
If that is the standard format, You can use split()
var str = 'milton_1';
alert(str.split('_')[1]);
You don't need regex for this. The following code in enough
var str = "milton_0";
str = str.substring(0,str.indexOf("_"));
I'm not sure how specific or broad you want to be, but you can try this:
var starter = "milton_1";
var specialVal = "asdf";
var re = /^(milton_)(\d+)$/;
var replaced = starter.replace(re, function (match, p1) {
return p1 + specialVal;
});
console.log(replaced);
http://jsfiddle.net/ne4cD/
This will match a string starting with "milton_" and ending with digits. It replaces any digits after the "_" with the specialVal value.
An example of simply incrementing that number is:
var starter = "milton_1";
var re = /^(milton_)(\d+)$/;
var replaced = starter.replace(re, function (match, p1, p2) {
return p1 + (+p2 + 1);
});
console.log(replaced);
http://jsfiddle.net/ne4cD/2/
UPDATE:
If the "milton" part isn't static, then you're really only targeting the "_" with digits after it. So something like this:
var starter = "asdfkjlasdfjksadf_1";
var specialVal = "asdf";
var re = /(_)(\d+)/g;
var replaced = starter.replace(re, function (match, p1) {
return p1 + specialVal;
});
console.log(replaced);
http://jsfiddle.net/ne4cD/3/
And maybe a little better to see: http://jsfiddle.net/ne4cD/4/
First of all you need them as list for handling easily.
var listOfStrings = yourStringObject('whateverYourCharacterUnderEachWord').ToList<string>();
After that you need to get rid of number for each string in the list and add what you want.
foreach(string word in listOfStrings){
word = word.Substring(0,word.IndexOf('_')+1);
word = word + "characterThatYouWantToAddHere"
}