Javascript regex matching syntax not working [duplicate] - javascript

This question already has an answer here:
Javascript regex match fails on actual page, but regex tests work just fine
(1 answer)
Closed 5 years ago.
I would like to test a string to ensure it has the following pattern:
asas/asas2/asas
The charatcers in between the slashes can be letters, digits or both.
I have a working example here, although i'm sure it could be improved.
Regex Example
But when tested in jsfiddle it doesn't work
Jsfiddle Example
var str = 'dfdfdf/dfdf/dfdf';
var patt = new RegExp("/(^\w+\/\w+\/\w+$)/g");
var res = patt.test(str);
alert(res);
The above code example always returns false.

Remove the quotes new RegExp(/(^\w+\/\w+\/\w+$)/g);

You just have to remove quotes.
var str = 'dfdfdf/dfdf/dfdf';
var patt = /(^\w+\/\w+\/\w+$)/g;
var res = patt.test(str);
alert(res);

Please try this code:
var str = 'dfdfdf/dfdf/dfdf';
var patt = new RegExp(/(^\w+\/\w+\/\w+$)/g);
var res = patt.test(str);
alert(res);
console.log(res);
Thanks

Related

How to delete all words with "-" before in Javascript [duplicate]

This question already has answers here:
Regex, replace all words starting with #
(5 answers)
Closed 5 years ago.
I'm totally new to regex and can't figure out how to realize it via Javascript.
For example, I have the string var string = "-just an example -string for stackoverflow". The expected result is string = "an example for stackoverflow".
Thanks in advance
Try this:
-\w+\s+
and replace by empty
Regex Demo
const regex = /-\w+\s+/gm;
const str = `-just an example -string for stackoverflow`;
const subst = ``;
const result = str.replace(regex, subst);
console.log(result);
Try this with simple forEach.
var string = "-just an example -string for stackoverflow";
var strArray = string.split(' ');
strArray.forEach(function(value, i){
if(value.startsWith('-')){
strArray.splice( i, 1 )
}
});
console.log(strArray.join(' '));

How can I do string replace in jquery [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 6 years ago.
I have this code
$("#title").keyup(function(){
var titleval = $("#title").val();
var res = titleval.replace(" ", "-");
$("#newsurl").val(res);
});
to replace spaces into dash to get URL like this
wordone-wordtow-wordthree
but i have problem with this code it's just replace first space like this
wordone-wordtow wordthree
How can i solve this problem
You need to do a global match, you can do this with a regex
var res = titleval.replace(/\s/g, "-");
Though String.prototype.replace does support having flags passed, this is deprecated in firefox and already doesn't work in chrome/v8.
Alternate method (if regex is not mandatory) could be to split and join
var res = titleval.split(" ").join("-");
or
var res = titleval.split(/\s+/).join("-");
Use regex with global flag
titleval.replace(/\s/g, "-");
try like this:
$("#title").keyup(function(){
var titleval = $("#title").val();
var res = titleval.replace(/\s+/g, '-');
$("#newsurl").val(res);
});

JS remove everything after the last occurrence of a character [duplicate]

This question already has answers here:
Remove everything after last backslash
(3 answers)
Closed 9 months ago.
Okay I have this
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
console.log(URL.substring(URL.lastIndexOf("/")));
Gives you "/remove-everything-before-the-last-occurrence-of-a-character"
How do I get "http://stackoverflow.com/questions/10767815/"
Here you are:
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
alert(URL.substring(0, URL.lastIndexOf("/") + 1));
Hope this helps.
Seems like a good case for a regular expression (can't believe no one has posted it yet):
URL.replace(/[^\/]+$/,'')
Removes all sequential non–forward slash characters to the end of the string (i.e. everything after the last /).
Generic solution
This is a generic function that also handles the edge case when the searched character or string (needle) is not found in the string we are searching in (haystack). It returns the original string in that case.
function trimStringAfter(haystack, needle) {
const lastIndex = haystack.lastIndexOf(needle)
return haystack.substring(0, lastIndex === -1 ? haystack.length : lastIndex + 1)
}
console.log(trimStringAfter('abcd/abcd/efg/ggfbf', '/')) // abcd/abcd/efg/
console.log(trimStringAfter('abcd/abcd/abcd', '/')) // abcd/abcd/
console.log(trimStringAfter('abcd/abcd/', '/')) // abcd/abcd/
console.log(trimStringAfter('abcd/abcd', '/')) // abcd/
console.log(trimStringAfter('abcd', '/')) // abcd
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
console.log(URL.substring(0,URL.lastIndexOf('/')+1));
//The +1 is to add the last slash
Try this jsfiddle or run the code snippet.
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
var myRegexp = /^(.*\/)/g;
var match = myRegexp.exec(URL);
alert(match[1]);
console.log(URL.substring(0, URL.lastIndexOf("/")+1));
Run this:
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
var temp = URL.split('/');
temp.pop();
var result = temp.join('/');
alert(result);
Try utilizing .match() with RegExp /^\w+.*\d+\//
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
var res = URL.match(/^\w+.*\d+\//)[0];
document.body.textContent = res;
Try an array based extraction like
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
snippet.log(URL.split('/').slice(0, 5).join('/'));
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<!-- To show result in the dom instead of console, only to be used in the snippet not in production -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Javascript: String.match() - pass string variable in regular expression [duplicate]

This question already has answers here:
Javascript Regexp dynamic generation from variables? [duplicate]
(4 answers)
Closed 7 years ago.
I tried to rewrite the method (part of tutorial on w3schools).
The problem is to make a variable string to become part of the regular expression.
Tutorial Sample code:
function myFunction() {
var str = "The rain in SPAIN stays mainly in the plain";
var res = str.match(/ain/gi);
console.log(res)
}
I tried:
function myFunction() {
var str = "The rain in SPAIN stays mainly in the plain";
var test = "ain";
var re = "/"+test+"/gi";
var res = str.match(re);
console.log(res);
}
The way I tried did not work.
Use the regex constructor, like:
function myFunction() {
var str = "The rain in SPAIN stays mainly in the plain",
test = "ain",
re = new RegExp(test, 'gi'),
res = str.match(re);
console.log(res);
}
You need to use RegExp constructor if you want to pass a value of variable as regex.
var test = "ain";
var re = new RegExp(test, "gi");
If your variable contains special chars, it's better to escape those.
var re = new RegExp(test.replace(/(\W)/g, "\\$1"), "gi");
Note that you pass a string to match. If we follow the documentation, this will do a new RegExp(test). So you should avoid / and /gi strings and add corresponding flags to the RegExp constructor: the default constructor doesn't add neither global search (g) nor case insensitive search (i).
So the solution to your problem:
var str = "The rain in SPAIN stays mainly in the plain";
var test = "ain";
var res = str.match(new RegExp(test, "gi"));
This will returns :
Array [ "ain", "AIN", "ain", "ain" ]
Note :
The form str.match(test, "gi"); works only in Firefox browser but is deprecated and throws a console warning from Firefox 39 (see RGraham comment).
Yes match() not works with string literals
You can use var re = new RegExp(test,"gi");
var str = "The rain in SPAIN stays mainly in the plain";
var test = "ain";
var re = new RegExp(test,"gi");
var res = str.match(re);
console.log(res);
You could have searched for "dynamic regular expressions" and you would have found:
Javascript Regexp dynamic generation from variables?
or Use dynamic (variable) string as regex pattern in JavaScript which both describe it very well.

Getting the last number in a string (JavaScript)

var str = "7-Dec-1985"
var str = "12-Jan-1703"
var str = "18-Feb-1999"
How would I got about pulling just the year out of the string? I have tried a number of different RegExp but none seem to be working.
I would have expected re = new RegExp(/(\d+)\D*\z/); To have worked but sadly it did not.
Any suggestions would be very appreciated
this should do it
var year = str.match(/\d+$/)[0];
Since all of your str(s) use - as a separator, this will work for you:
var str = "7-Dec-1985",
arr = str.split('-'),
year = arr[2];
console.log(year);
I'd try: /.*(\d{4})$/
Test your regex's here: http://www.regular-expressions.info/javascriptexample.html

Categories

Resources