capture string between characters with jquery - javascript

I have a variable which contains "j_id0:j_id11:i:f:pb:d:MyFieldName.input" (without the quotes).
Now I would like to capture "MyFieldName".
I had this:
var test = "j_id0:j_id11:i:f:pb:d:MyFieldName.input";
var testRE = test.match(":(.*).input");
console.log("old text: " + test);
console.log("new text: " + testRE[1]);
which outputs this:
old text: j_id0:j_id11:i:f:pb:d:MyFieldName.input
new text: j_id11:i:f:pb:d:MyFieldName
So what I need is telling him that I want everything between the last occurence ":" and ".input", because now he finds the first ':' and stops there.
Any ideas how I can realise this?
Thanks!

One option that remains (among, presumably, many others) is:
var str = "j_id0:j_id11:i:f:pb:d:MyFieldName.input",
fieldName = str.substring(str.lastIndexOf(':') + 1, str.lastIndexOf('.'));
JS Fiddle demo.
References:
String.lastIndexOf().
String.substring().

This regex will work:
.*:(.*)\.input

You could try this without regular expressions:
var test = "j_id0:j_id11:i:f:pb:d:MyFieldName.input";
var fieldName = test.split(':').pop().split('.')[0];

The problem with your regex is that it matches the first :, and then captures everything (.*) up until .input. To avoid this, you can make sure that your capture between : and .input cannot include more :.
This regex should work for you:
/:(\w+)\.input/
Fiddle
var test = "j_id0:j_id11:i:f:pb:d:MyFieldName.input";
var testRE = test.match(/:(\w+)\.input/)
console.log("old text: " + test);
console.log("new text: " + testRE[1]); //MyFieldName
Group 1 will contain your field name.
I think the above should work for you, but if you need more than \w characters, you could use this instead to allow for things like "...:My.Field.Name.input" and capture "My.Field.Name":
/:([^:]+)\.input/

Related

When passing 2 variables in jQuery selector there's no result but when typing the same string output it does

for example:
var a = "1234";
var b = "line1\\\\.5";
now this line of code:
"#" + a + b;
puts out this string
"#1234line1\\.5"
and when I enter it in the selector like this:
$("#1234line1\\.5")
it shows the correct element
but $("#" + a + b)
Does not
Thanks in advance for any suggestions
I'm surprised it works in the console, the id selector is invalid. CSS id selectors cannot start with a digit. You can escape it, though:
var a = "\\31 234"; // \\31 = 1, then you need the space to terminate the escape
var b = "line1\\.5"; // Removed a pair of \\ from this, I assume you
// don't have a backslash in the id
$("#" + a + b).html("Found it");
This works, for instance: Live Example
<div id="1234line1.5"></div>
<script>
(function() {
"use strict";
var a = "\\31 234";
var b = "line1\\.5";
$("#" + a + b).html("Found it");
})();
</script>
If you really have a backslash in the id, the escape for a backslash is \5c, which you write in a string literal as \\5c, so: Live Example
<div id="1234line1\.5"></div>
<script>
(function() {
"use strict";
var a = "\\31 234";
var b = "line1\\5c \\.5";
$("#" + a + b).html("Found it");
})();
</script>
One thing first: Depending on the Doctype you use, IDs may not contain backslashes or start with numbers. Please check that first.
A backslash within a Javascript string indicates that the next character should be escaped. So if you want to use a backslash within your name, then you have to escape it with a leading backslash.
If you write a code like this:
$('#abc\\\\d')
then it refers to an element with the ID abc\\d (which may be illegal to use), because both of your backslashes are being escaped.
The problem is not that the id starts with a digit, Html 5 supports this kind of ids
the problem is that you put 4 backslash instead of 2
so instead of searching for
#1234line1\.5
you searched for
#1234line1\\.5
just change it to
var b = "line1\\.5";
and it will work fine

Validating a string pattern in regex

I have the following string:
/xyz/10.2005/abc.d10.1/example
Here what I want to validate is, there should not be a space after "/xyz/".
Like It should not accept if the string is:
/xyz/ 10.2005/abc.d10.1/example
But it should accept if the string is:
10.2005/abc.d10.1/example
How can I modify the following regex to validate the above thing??
REGEX- "^\\S*((10(\\.\\d+)+)\\/([^\\/]+)(\\/\\d+[\\.+[a-zA-Z\\d]]*)?)"
Could someone help me??
This may be what you are looking for (it's a literal, you can convert it to a string if you really need to use the RegExp constructor):
var re = /^(\/\w+\/10|\s*10)\.\d+\/\w+\.\w\d+\.\d\/\w{7}/;
var s = '/xyz/10.2005/abc.d10.1/example';
var t = '/xyz/ 10.2005/abc.d10.1/example';
var u = ' 10.2005/abc.d10.1/example';
console.log(
's:' + re.test(s) + '\n' + // true
't:' + re.test(t) + '\n' + // false
'u:' + re.test(u) + '\n' // true
);
It does more than just validate the space after the /xyz/ part, I hope the rest is what you want.
actually you need to make it a lazy regex
just change it to this
^\\S*?((10(\\.\\d+)+)\\/([^\\/]+)(\\/\\d+[\\.+[a-zA-Z\\d]]*)?).*
see those ? and .* at the end
demo here : http://regex101.com/r/zJ7yX8
Here's a long RegEx:
/(?:\/[a-z]+\/)?\10\.\d{4}\/[a-z]{3}\.[a-z]\d{2}\.\d\/[a-z]{7}/i
// or the following if you don't want exact occurrences
/(?:\/[a-z]+\/)?10\.\d+\/[a-z]+\.[a-z]\d+\.\d\/[a-z]+/i
Matches:
/xyz/10.2005/abc.d10.1/example
10.2005/abc.d10.1/example
?: makes the group non-capturing.
The ? after the bracket-end symbolize it is optional.
Next is fairly simple RegEx.
For more explanation, here's a demo

line break introduction in confirm message string

I have a confirmation pop-up dialog in which I am passing a variable which is a comma separated string.
How can I replace the commas and introduce a line break?
I tried using replace. I tried passing '\n' separated list from back-end. But nothing seems to work — though a normal confirm() used for testing purposes is working fine.
var listcontrol = document.getElementById(id3);
var List = listcontrol.innerText;
var finallist = List.replace("\n", "\n");
if (checkboxCell.checked == false) {
if (labelCell.innerText == "Yes") {
confirm("The selected exam is present in the following certifications: " + "\n" + finallist + "\n" +
"Uplanning this exam here would unplan the same exam under other certification(s) also.");
}
}
In your code you are replacing "\n" with "\n", which would make no difference. You want to replace "," with "\n" instead, right?
var string = "Demetrius Navarro,Tony Plana,Samuel L. Jackson";
alert(string);
alert(string.replace(/,/g, "\n"));​​​​
Live test - http://jsfiddle.net/9eZS9/
Js replace is,
string.replace(searchvalue,newvalue)
var finallist = List.replace(/,/g, "\n");
If your "pop-up dialog" is a custom html/css-based dialog then newline characters would be treated (more or less) the same as space characters. You'd need to use <br> elements instead, so:
var finallist = List.replace(/,/g, "<br>");
Note the use of the regex as the first argument for replace() - this is needed in order to do a global replace.
For use in a standard confirm you'd need newline characters like you were doing, but with a regex rather than a string for the replace() search term:
var finallist = List.replace(/,/g, "\n");

Replace first occurance of char with * then the rest with a ' '

I have a sentence (this is a dumb example sentence ) that looks like this:
I_like_to_program__.
I need a function to make it look like this:
I*like to program.
I have written this expression:
var myExpression = new RegExp("\\_", "g");
return myString.replace(myExpression, " ").trim();
That'll output: "I like to program." --I'm close. I just need the first space to replace with a * to make it look like I*like to program.
mystring.replace("_", "*")
.replace(/_/g, " ");
Or you could avoid the regex altogether like this:
mystring.replace("_", "*")
.split("_")
.join(" ");
If you don't add g, javascript's replace default to only one replacement :
return myString.replace(/\__/, "").replace(/\_/, "*").replace(/\_/g, " ");
var myString = "I_like_to_program__.";
var result = myString.replace(/\_/g, " ").replace(" ", "").replace(" ", '*');
alert(result);
The easiest thing I can think of is to do it in two steps-- replace the first instance with *, then iterate again and replace globally with " "
var myString = "I_LIKE_TO_PROGRAM";
var myExpression = new RegExp("\_");
myString = myString.replace(myExpression, "*").trim();
var newExpression = new RegExp("\_", "g");
alert(myString.replace(newExpression, " ").trim());
I first replace all _ replace with "", after doing this in we we will have program .
So In second replace I am removing (program .) this space and in third replace I put * in first place.
DEMO
http://jsfiddle.net/saorabhkr/QV9qH/

Simple regex: how do I say: "it's okay to have an " s " or " es " or " 's " at the end of the word, match those too."?

I'm using Jquery(don't know if that's relevant), here's the regex:
var re = new RegExp('\\b' + a_filter + '\\b');
So it matches whole words in the variabe a_filter which has a bunch of words in it. Right now it will match 'wrench', but not 'wrenches'. It will match 'chair', but not 'chairs', it will match "john" but not "john's". I've been trying but I can't figure it out.
Can someone please help me adjust my regex above to allow for these at the end of the word?
s es 's are what I want to allow at the end of a word match, so i don't have to include every single possible variation of each word. I think that's all the word endings that there really are that someone would type, if you know more, it would be great to get help, THANKS!
EDIT: here's my jsfiddle, maybe I had a_filter mixed up with filter_tags, I think i'm doing it backwards, ugh. ???
http://jsfiddle.net/nicktheandroid/mMTsc/18/
I have a group of your endings after the filter concatenation, with ? to require 0 or 1 match.
var a_filter = "wrench";
var re = new RegExp('\\b' + a_filter + '(s|es|\'s)?\\b');
alert( re.test("wrench's") );
Example: http://jsfiddle.net/qctAG/ (alert() warning. you'll get 4 of them)
You want something that looks like this:
var re = new RegExp('\\b' + a_filter + '(s|es|\'s)?\\b');
Of course, that will not match all plurals (e.g. oxen, geese) and it will match words that don't exist (e.g. sheeps).
This works for me...assuming you have an array!
var a_filter = ["wrench","wrenches","wrench's"];
for(var i=0; i < a_filter.length; i++){
var re = new RegExp('\^' + a_filter[i] + '\$');
document.write(re.test("wrench's") + " " + a_filter[i] + "<br />");
}
Here is the fiddle: http://jsfiddle.net/XCARd/2/
Play with the re.test() to see it match.

Categories