Replace a substring and optionally the subsequent character - javascript

How can I replace the character following a certain substring, if it is a -? I am using a regular expression to match and replace the substring itself, but I also want to match the character immediately following that if it is a hyphen.
For example :
$('.classg').on("click", function() {
idq = $(this).attr('name');
var _href = $('.classh').children("a").attr("href");
$('.classh').children("a").attr("href", _href.replace(idq, ''));
// ...
});
HTML:
<p class="classg">Answer</p>
<li class="classh" name="16992964">Multiquote</li>
After the replace of idq, I want to be able to determine what is the next character on the _href string just after the string idq. If the character is - then I want to replace it with '' (the blank string). If it's something else, I want it to be ignored.

Use the ? regex operator, which optionally matches the preceding element. If it is there, it will be replaced. If not, only the original ID is replaced.
Since the rest of your pattern is in a variable, you can construct the RegExp object like this: var re = new RegExp(idq + "\\-?");.
This matches the first occurrence of idq, optionally followed by a hyphen (-).
$('.classg').on("click", function() {
var idq = $(this).attr('id'); // ID will be a number example : 998352
var _href = $('.classh').children("a").attr("href");
var re = new RegExp(idq + "\\-?");
$('.classh').children("a").attr("href", _href.replace(re, ''));
});

Related

Replace after char '-' or '/' match

I'm trying to execute regex replace after match char, example 3674802/3 or 637884-ORG
The id can become one of them, in that case, how can I use regex replace to match to remove after the match?
Input var id = 3674802/3 or 637884-ORG;
Expected Output 3674802 or 637884
You could use sbustring method to take part of string only till '/' OR '-':
var input = "3674802/3";
var output = input.substr(0, input.indexOf('/'));
var input = "637884-ORG";
var output = input.substr(0, input.indexOf('-'));
var input = "3674802/3";
if (input.indexOf('/') > -1)
{
input = input.substr(0, input.indexOf('/'));
}
console.log(input);
var input = "637884-ORG";
if (input.indexOf('-') > -1)
{
input = input.substr(0, input.indexOf('-'));
}
console.log(input);
You can use a regex with a lookahead assertion
/(\d+)(?=[/-])/g
var id = "3674802/3"
console.log((id.match(/(\d+)(?=[/-])/g) || []).pop())
id = "637884-ORG"
console.log((id.match(/(\d+)(?=[/-])/g) || []).pop())
You don't need Regex for this. Regex is far more powerful than what you need.
You get away with the String's substring and indexOf methods.
indexOf takes in a character/substring and returns an integer. The integer represents what character position the character/substring starts at.
substring takes in a starting position and ending position, and returns the new string from the start to the end.
If are having trouble getting these to work; then, feel free to ask for more clarification.
You can use the following script:
var str = '3674802/3 or 637884-ORG';
var id = str.replace(/(\d+)[-\/](?:\d+|[A-Z]+)/g, '$1');
Details concerning the regex:
(\d+) - A seuence of digits, the 1st capturing group.
[-\/] - Either a minus or a slash. Because / are regex delimiters,
it must be escaped with a backslash.
(?: - Start of a non-capturing group, a "container" for alternatives.
\d+ - First alternative - a sequence of digits.
| - Alternative separator.
[A-Z]+ - Second alternative - a sequence of letters.
) - End of the non-capturing group.
g - global option.
The expression to replace with: $1 - replace the whole finding with
the first capturing group.
Thanks To everyone who responded to my question, was really helpful to resolve my issue.
Here is My answer that I built:
var str = ['8484683*ORG','7488575/2','647658-ORG'];
for(i=0;i<str.length;i++){
var regRep = /((\/\/[^\/]+)?\/.*)|(\-.*)|(\*.*)/;
var txt = str[i].replace(regRep,"");
console.log(txt);
}

Need help finding a plus sign using javascript regex

I am using the code below to find a match for a plus sign but it keeps returning false. I am not sure what I am doing wrong. Any help will be really appreciated it. Thanks!
var str = '+2443';
var result = /d\+1/.test(str);
console.log(result); // true
var str = '+2443';
var result = /\+/.test(str);
console.log(result); // true
Your /d\+1/ regex matches the first occurrence of a d+1 substring in any string.
To check if a string contains a +, you do not need a regex. Use indexOf:
var str = '+2443';
if (~str.indexOf("+")) {
console.log("Found a `+`");
} else {
console.log("A `+` is not found");
}
A regex will be more appropriate when you need to match a + in some context. For example, to check if the string starts with a plus, and then only contains digits, you would use
var str = '+2443';
var rx = /^\+\d+$/;
console.log(rx.test(str));
where ^ assets the position at the end of the string, \+ matches a literal +, \d+ matches 1+ digits and the $ anchor asserts the position at the end of the string.

Regular expression to test exact word with a trailing dot

I am having a dynamic variable which I need to match against a source.
Source: 'text clientLogin padding float';
search: '.clientLog'
The search text has a leading dot('.') which should be omitted while comparing.
For the above example I should:
Get the part of search after '.'(dot)
Check the source for the search text i.e clientLog & return true if whole word matches.(in this example it should return false as source has clientLogin).
I am trying to use RegEx to achieve this
var regEx = new RegExp(k); // k is the search text
if(regEx.test(classNames)){....
Above code is inside jQuery.each,k is the key of the object which is being iterated.I did not figure out how to omit the '.' but read somewhere to implement Word Boundries for the exact match.
Please suggest.
thanks
Try this:
var
source = 'text clientLogin padding float',
search = '.clientLog',
pattern = '\\b'+search.replace(/^\./, '')+'\\b',
result = new RegExp(pattern).test(source);
Notes:
We strip off the leading '.' from the search string while building the pattern
We use word boundary markers (\b). This helps ensure that "login" is not considered a valid match for "log", for example, like in your case.
The double-escaping (\\b) is necessary as we're building our pattern as a string - this is necessary for dynamic patterns fed to the RegExp constructor.
Stripping text
In JavaScript, you can strip text with the substring() method like this:
var str = "Hello World!";
var sub_str = str.substring(1, str.length);
In substring(x, y), x is the starting index of the new string, y is the ending index. The indecies in JavaScript start at 0, so we have to use the next index to omit the first character in the string.
You can also read it up here on W3Schools.
Regular Expressions
You can search RegEx patterns in strings like this:
var str = "Hello World!";
var pos = str.search(/World/); // Attention: No quotes here!
pos equals the index of the first match of the given expression. If your expression did not match your string, then pos will equal -1.
Note, that str.search(/World/); is basicly the same as str.search(new RegExp("World"));
You can also read it up here on W3Schools.
To check, if your string contains that classname, you could do this:
var str = "classname1 classname2 classname3";
var search_str = ".classname2";
if(str.search(new RegExp("\\b(" + search_str.substring(1, search_str.length) + ")\\b")) > -1){
// classname found
} else {
//classname not found
}

Am I using pattern matching correctly here?

I have the following code. Given that the variable u1 can be any of the following:
NBSLoan|Accept|PPI+No|60Months
NBSLoan|Refer|PPI+No|60Months
DeBSLoan|Accept|PPI+No|60Months
Also, the last part 60Months will always be different, can I pattern match using the following JavaScript? Do I need to put in a special character for the pipe | symbol? Or will this not work as I'm trying to match only the first part of a longer string?
<script type="text/javascript">
var u1 = 'NBSLoan|Accept|PPI+No|60Months';
var n_accept = /^NBSLoan|Accept$/;
var n_refer = /^NBSLoan|Refer$/;
var d_accept = /^DeBSLoan|Accept$/;
if (u1.match(n_accept)) {
var pvnPixel = '<img src="https://url1.com"/>';
document.write(pvnPixel);
}
else if (u1.match(n_refer)) {
var pvnPixel2 = '<img src="url2.com"/>';
document.write(pvnPixel2);
}
else if (u1.match(d_accept)) {
var pvnPixel3 = '<img src="url3.com"/>';
document.write(pvnPixel3);
}
</script>
Do I need to put in a special character for the pipe | symbol? Or will this not work as I'm trying to match only the first part of a longer string?
Both.
You need to escape the pipe symbol with a backslash to match a literal pipe character. Without the backslash it means alternation.
You also need to remove your end of line anchor.
Try this regular expression:
/^NBSLoan\|Accept/
Why don't you first split fields with split('|'):
function dispatch(u) {
var parts = u.split('|'),
key = parts[0] + "_" + parts[1];
disp_table = {
'NBSLoan_Accept':'url1.com',
'NBSLoan_Refer':'url2.com',
'DeBSLoan_Accept':'url3.com'
},
url = disp_table[key];
url && document.write("<img src=\""+url+"\"/>");
}
You want to also remove the $ (it signifies the end of string) or add a .* to capture all the other characters:
To lose the end:
/^NBSLoan\|Accept/
To match and capture the other characters:
/^NBSLoan\|Accept.*$/

How can I remove all characters up to and including the 3rd slash in a string?

I'm having trouble with removing all characters up to and including the 3 third slash in JavaScript. This is my string:
http://blablab/test
The result should be:
test
Does anybody know the correct solution?
To get the last item in a path, you can split the string on / and then pop():
var url = "http://blablab/test";
alert(url.split("/").pop());
//-> "test"
To specify an individual part of a path, split on / and use bracket notation to access the item:
var url = "http://blablab/test/page.php";
alert(url.split("/")[3]);
//-> "test"
Or, if you want everything after the third slash, split(), slice() and join():
var url = "http://blablab/test/page.php";
alert(url.split("/").slice(3).join("/"));
//-> "test/page.php"
var string = 'http://blablab/test'
string = string.replace(/[\s\S]*\//,'').replace(/[\s\S]*\//,'').replace(/[\s\S]*\//,'')
alert(string)
This is a regular expression. I will explain below
The regex is /[\s\S]*\//
/ is the start of the regex
Where [\s\S] means whitespace or non whitespace (anything), not to be confused with . which does not match line breaks (. is the same as [^\r\n]).
* means that we match anywhere from zero to unlimited number of [\s\S]
\/ Means match a slash character
The last / is the end of the regex
var str = "http://blablab/test";
var index = 0;
for(var i = 0; i < 3; i++){
index = str.indexOf("/",index)+1;
}
str = str.substr(index);
To make it a one liner you could make the following:
str = str.substr(str.indexOf("/",str.indexOf("/",str.indexOf("/")+1)+1)+1);
You can use split to split the string in parts and use slice to return all parts after the third slice.
var str = "http://blablab/test",
arr = str.split("/");
arr = arr.slice(3);
console.log(arr.join("/")); // "test"
// A longer string:
var str = "http://blablab/test/test"; // "test/test";
You could use a regular expression like this one:
'http://blablab/test'.match(/^(?:[^/]*\/){3}(.*)$/);
// -> ['http://blablab/test', 'test]
A string’s match method gives you either an array (of the whole match, in this case the whole input, and of any capture groups (and we want the first capture group)), or null. So, for general use you need to pull out the 1th element of the array, or null if a match wasn’t found:
var input = 'http://blablab/test',
re = /^(?:[^/]*\/){3}(.*)$/,
match = input.match(re),
result = match && match[1]; // With this input, result contains "test"
let str = "http://blablab/test";
let data = new URL(str).pathname.split("/").pop();
console.log(data);

Categories

Resources