I have inputs with names:
<input type="text" name="data[Site][search]">
<input type="text" name="data[Site][name]">
I want to get when I click only:
search
name
etc.
My JS in click event
var reg = /data\[Site\]\[\d\]/g;
var test = $(this).attr("name").match(reg);
console.log(test);
But console display null. What is wrong in my reg?
Try with using this:
var reg = /data\[Site\]\[(.+)\]/g; //Capture the characters between []
var test = reg.exec($(this).attr("name"));
console.log(test[1]); //Output search | name
Demo
You're using \d which means digits only, you're also not specifying a quantifier so you'll only capture one digit at most, i.e:
data[Search][1]
You could use \S which is any non-whitespace character. You want to do this for at least one character (as you shouldn't have data[Search][] and you'll also want to capture the name, so throw in some (). You could switch \S to specific characters using character sets, for example [A-Za-z0-9].
Anyhow, your modified example should not look something like this:
var reg = /data\[Site\]\[(\S+)\]/g;
var test = $(this).attr("name").match(reg);
console.log(test);
You'll be able to pull the actual value from the match captures using test[1].
Related
I'm trying to replace some words in a string with .replace(desiredWord,""), to remove those words from that string.
I have a string which is like this "xsmall small medium" and I'm trying to remove "small" from that string in some events, but it sometimes removes small of xsmall also, which is not my intention..
Is there any way to restrict replace method or I should use another method?
I want to replace or remove specific word, not letters.
The following should work:
If you pad your desiredWord with the word boundary \b operator it will work without false positives.
const sampleString = "xsmall small medium";
console.log(sampleString.replace(/\bsmall\b/g, "test"));
With variable
document.querySelector("#replace").addEventListener("click", (e) => {
debugger
const value = document.querySelector("#change").value;
//escape the operators in the regexp!
const regex = new RegExp("\\b"+value+"\\b", "g");
document.querySelector("#text").value = document.querySelector("#text").value.replace(regex, "test");
}, true);
<input readonly id="text" value="xsmall small medium" /><br />
<input id="change"><button id="replace">Replace</button>
You can use a RegEx expression for this.
You can use these in the replace method directly.
A way to check this is using the next expression: \bsmall
The result of this is as follow :
string.replace(\bsmall, "")
\b will check if the characters are from 1 and only 1 word
You could exclude letters before explicitly:
const sampleString = "xsmall small medium";
console.log(sampleString.replace(/([^a-z])(?=small)/ig, "$1x");
This regular expression reads, "Not a letter, followed by (but not captured) 'small', replaced with whatever the non-letter was, followed by an x."
or the same thing using the word boundary feature, just be sure not to delete it too:
const sampleString = "xsmall small medium";
console.log(sampleString.replace(/(\b)(?=small)/ig, "$1x");
This one reads, "Any word boundary, followed by 'small' (but without 'small' forming part of the replacement), replaced by the word boundary and then an 'x'.
My regex: <br>![a-z]+(?=<br>)
fooword1<br>!fooword2<br>fooword3
I am trying to get word that begins with "!", like "!fooword2" and exists between <br> tags. But when i apply this <br>![a-z]+(?=<br>) , i get "<br>!fooword2".
I just need to select "!fooword2" .I mean i don't need to select first <br>.
So what is wrong with my regex?
What about:
<br>(![a-z0-9]+)<br>
as a regex?
Since JS does not support LookBehind, You could use groups to exclude the first <br>
var String = "fooword1<br>!fooword2<br>fooword3";
var Regexp = /<br>(![a-z]+\d)<br>/g;
var match = Regexp.exec(String);
console.log(match[1])
Another option will be using Positive Lookahead at the end with <br>, and relying on the ! at the beginning:
![a-z]+\d(?=<br>)
Demo: https://regex101.com/r/kRzoQB/3
This might work better. It doesn't depend on the tag that is used.
var str = 'fooword1<br>!fooword2<br>fooword3',
regi = /(!\w*\d{1})/g,
obj = regi.exec(str);
console.log(obj[0]);
You need the [0] because exec returns an array and the value that you are looking for is at the zero index of that array.
I try to get the 00-8.
Why this code do not returns me the 00-8 ?
<script>
var pageDetailsSecond = "a='00-8'b='13-'a+='00-2'b+='3333'c='4'";
var phone1 = pageDetailsSecond.match("a='(.*)'");
var phone1 = phone1[0];
var card_Phone = phone1;
alert(card_Phone);
</script>
Actually I get a='00-8'.
Because what you try to match includes a=....
But when you find it, you can strip it from the match found.
Checked with jsfiddle: http://jsfiddle.net/pbo5x9dx/
var pageDetailsSecond = "a='00-8'b='13-'a+='00-2'b+='3333'c='4'";
alert(pageDetailsSecond)
var phones = pageDetailsSecond.match("a='(.*?)'");
var phone1 = phones[1];
alert(phone1)
** edit: ** fix for non-greedy match, checked with http://jsfiddle.net/pbo5x9dx/1/
Because the array returned by match() will contain the entire match in the first array slot, and the capture groups in subsequent elements.
The array contents will be:
[
[0] = "a='00-8'",
[1] = '00-8'
]
What you want is phone1[1] instead of phone1[0], which contains just the portion of the match specified by your capture group (.*).
Based on the updated question, the regex pattern should be changed to:
"a='(.*?)'"
By default, regex patterns try to match as much as possible (known as "greedy"). The pattern is saying "match any number of any characters between ' characters. This now includes 00-8'b='13-'a+='00-2'b+='3333'c='4. By adding the ?, this changes the behaviour to "lazy". In other words, match as little as possible, and your regex is back to matching only 00-8 as before.
HI i need to split some part of variable value
in my html file i got a dynamic value of variable some thing like this
product/roe_anythin_anything-1.jpg
product/soe_anything_anything-2.jpg
i need to remove the before
/slashpart
and after
_ part
which should return the roe or soe part
i have use a function
<script>
function splitSize(){
$('#splitSize').each(function(index) {
var mystr = $(this).html();
var mystr1 = /product\/(.*)-.*/.exec(mystr);
$(this).html(mystr1[1]);
//$(this).html(mystr1[0]);
});
}
splitSize();
</script>
with which i got roe_anythin_anything successfully i just need to remove now after `
_ part
`
please suggest how can i do this
This is as you asked using split . You can use RegEx to make it simpler
var myStr = 'product/roe-1.jpg' ;
myStr = myStr.split('/')[1];
myStr = myStr.split('-')[0];
Working JS Fiddle
Use regex group capture
var myStr = 'product/roe-1.jpg';
var result = /product\/(.*)-.*/.exec(myStr)[1];
Break down:
/product\/
matches the initial product string and the / character (escaped so its not interpreted as the end of the regex)
The
(.*)
Matches your roe characters and keeps them in a 'capture group' - everything up to but not including the hyphen
Then the hyphen is matched, then anything else.
This returns a 2 element array. Item 0 is the whole string, item 1 is the contents of the capture group.
See How do you access the matched groups in a JavaScript regular expression? for more details
How it is better to check (test) if text contains only characters from set (for example if text contains only punctuation marks)
var regex = /[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g
res = text.replace(regex, '')
if (res) return false
so I made it with replace is it possible to do it with regex.test?
Yes it is. There are two possibilities. One is, that you use anchors to assert that the full string is made up of these:
var regex = /^[\.,-\/#!$%\^&\*;:{}=\-_`~()]+$/;
if(regex.test(text))
Alternatively you can use a negated character class and see whether it matches and then again negate the result
var regex = /[^\.,-\/#!$%\^&\*;:{}=\-_`~()]/;
if(!regex.test(text))
Note that ,-\/ is a range that includes ,-./. This is redundant and may become a source of errors if the character class is ever changed. You might want to simplify your character class to:
[.,\/#!$%^&*;:{}=_`~()-]
(Or the negated version of that, depending on which approach you choose.)