Am I using pattern matching correctly here? - javascript

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.*$/

Related

String replace a url with part of the same url in javascript

I have string that contains a random url:
http://google.com/vocab/prefix#Billy
That needs to be transformed so that everything up to, and including the first # is replaced with the value between the last / and the first # followed by a :.
The result would be:
prefix:Billy
More examples:
http://some.url/a/path#elephant --> path:elephant
http://random.com/cool/black/beans/thing#Bob --> thing:bob
I understand how to capture the prefix part /([^\/]+(?=#))/, but I'm struggling to do a string replace because I can't figure out how to capture the part I need to replace.
myString.replace(/([^\/]+(?=#))/, '$1:')
I would prefer to use string.replace with regex if at all possible
When using replace method you need to match all the patterns you want to replace instead of just the part you need to keep; Here are two options:
let s = 'http://google.com/vocab/prefix#Billy'
// using greedy regex
console.log(s.replace(/.*\/([^#]+)#/, '$1:'))
// adapted from OP's attempt
console.log(s.replace(/.*?([^\/]+?)#/, '$1:'))
Note .* part to match the substring you want to discard, () to capture the pattern you want to keep, then reformat the output.
Try this code:
var myString = "http://google.com/vocab/prefix#Billy";
var hashIndex = myString.indexOf("#"); // find where the "#" is
for(var i = hashIndex; i > 0; i--) { // loop from "#" index *back* to closest "/" symbol
if(myString[i] == "/") break; // break loop when "/" is found
}
myString = myString.replace("#", ":"); // replace "#" with ":" as in your example
console.log(myString.substring(i, hashIndex); // output
Shortened:
var myString = "http://google.com/vocab/prefix#Billy".replace("#",":");
for(var i = myString.indexOf(":"); i > 0; i--) { if(myString[i] == "/") break; }
console.log(myString.substring(i, myString.indexOf(":");

Remove all content after last '\' is not working

I'm trying to rename a document, I want to remove all the content after the last '\' and then give it another name.
I did it like this but it doesn't seem to be working:
var newDocName = documentPath.replace(/\/$/, '');
var newDocName = newDocName + "\test.pdf";
The '\' doesn't get removed after the first line of code.
Any idea what am I doing wrong?
/\/$/ means you want to match a / if it's the last character in the string meaning this code would replace the very last / if, and only if, it's at the end of the string.
If you want to remove the content after the last \ then you can use a combination of split to split the string on \s then use slice to get everything but the last element. Finally, use join to bring them all back together.
var uri = 'path\\to\\my\\file.ext';
var parts = uri.split('\\');
var withoutFile = parts.slice(0, parts.length - 1);
var putItBackTogether = withoutFile.join('\\');
var voila = putItBackTogether + '\\new-file.name';
console.log(voila);
It is forward slash, use \\ istead.
Try to substitute it for:
var newDocName = documentPath.replace(/\\/$/, '');
Your REGEX has a bad format: you should escape your backquotes (\).
So it may be:
var newDocName = documentPath.replace(/[\\/]$/, '');
var newDocName = newDocName + "\\test.pdf";
This regular expression will search for \ or / at the end ($) of you path. You could use regex101 to test your regular expressions.
You also should consider not using regular expressions when you don’t need them:
var newDocName = documentPath[documentPath.length - 1] == "\\" ? documentPath + "test.pdf" : documentPath + "\\test.pdf";

Replace a substring and optionally the subsequent character

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, ''));
});

Extract string when preceding number or combo of preceding characters is unknown

Here's an example string:
++++#foo+bar+baz++#yikes
I need to extract foo and only foo from there or a similar scenario.
The + and the # are the only characters I need to worry about.
However, regardless of what precedes foo, it needs to be stripped or ignored. Everything else after it needs to as well.
try this:
/\++#(\w+)/
and catch the capturing group one.
You can simply use the match() method.
var str = "++++#foo+bar+baz++#yikes";
var res = str.match(/\w+/g);
console.log(res[0]); // foo
console.log(res); // foo,bar,baz,yikes
Or use exec
var str = "++++#foo+bar+baz++#yikes";
var match = /(\w+)/.exec(str);
alert(match[1]); // foo
Using exec with a g modifier (global) is meant to be used in a loop getting all sub matches.
var str = "++++#foo+bar+baz++#yikes";
var re = /\w+/g;
var match;
while (match = re.exec(str)) {
// In array form, match is now your next match..
}
How exactly do + and # play a role in identifying foo? If you just want any string that follows # and is terminated by + that's as simple as:
var foostring = '++++#foo+bar+baz++#yikes';
var matches = (/\#([^+]+)\+/g).exec(foostring);
if (matches.length > 1) {
// all the matches are found in elements 1 .. length - 1 of the matches array
alert('found ' + matches[1] + '!'); // alerts 'found foo!'
}
To help you more specifically, please provide information about the possible variations of your data and how you would go about identifying the token you want to extract even in cases of differing lengths and characters.
If you are just looking for the first segment of text preceded and followed by any combination of + and #, then use:
var foostring = '++++#foo+bar+baz++#yikes';
var result = foostring.match(/[^+#]+/);
// will be the single-element array, ['foo'], or null.
Depending on your data, using \w may be too restrictive as it is equivalent to [a-zA-z0-9_]. Does your data have anything else such as punctuation, dashes, parentheses, or any other characters that you do want to include in the match? Using the negated character class I suggest will catch every token that does not contain a + or a #.

Javascript Remove strings in beginning and end

base on the following string
...here..
..there...
.their.here.
How can i remove the . on the beginning and end of string like the trim that removes all spaces, using javascript
the output should be
here
there
their.here
These are the reasons why the RegEx for this task is /(^\.+|\.+$)/mg:
Inside /()/ is where you write the pattern of the substring you want to find in the string:
/(ol)/ This will find the substring ol in the string.
var x = "colt".replace(/(ol)/, 'a'); will give you x == "cat";
The ^\.+|\.+$ in /()/ is separated into 2 parts by the symbol | [means or]
^\.+ and \.+$
^\.+ means to find as many . as possible at the start.
^ means at the start; \ is to escape the character; adding + behind a character means to match any string containing one or more that character
\.+$ means to find as many . as possible at the end.
$ means at the end.
The m behind /()/ is used to specify that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary.
The g behind /()/ is used to perform a global match: so it find all matches rather than stopping after the first match.
To learn more about RegEx you can check out this guide.
Try to use the following regex
var text = '...here..\n..there...\n.their.here.';
var replaced = text.replace(/(^\.+|\.+$)/mg, '');
Here is working Demo
Use Regex /(^\.+|\.+$)/mg
^ represent at start
\.+ one or many full stops
$ represents at end
so:
var text = '...here..\n..there...\n.their.here.';
alert(text.replace(/(^\.+|\.+$)/mg, ''));
Here is an non regular expression answer which utilizes String.prototype
String.prototype.strim = function(needle){
var first_pos = 0;
var last_pos = this.length-1;
//find first non needle char position
for(var i = 0; i<this.length;i++){
if(this.charAt(i) !== needle){
first_pos = (i == 0? 0:i);
break;
}
}
//find last non needle char position
for(var i = this.length-1; i>0;i--){
if(this.charAt(i) !== needle){
last_pos = (i == this.length? this.length:i+1);
break;
}
}
return this.substring(first_pos,last_pos);
}
alert("...here..".strim('.'));
alert("..there...".strim('.'))
alert(".their.here.".strim('.'))
alert("hereagain..".strim('.'))
and see it working here : http://jsfiddle.net/cettox/VQPbp/
Slightly more code-golfy, if not readable, non-regexp prototype extension:
String.prototype.strim = function(needle) {
var out = this;
while (0 === out.indexOf(needle))
out = out.substr(needle.length);
while (out.length === out.lastIndexOf(needle) + needle.length)
out = out.slice(0,out.length-needle.length);
return out;
}
var spam = "this is a string that ends with thisthis";
alert("#" + spam.strim("this") + "#");
Fiddle-ige
Use RegEx with javaScript Replace
var res = s.replace(/(^\.+|\.+$)/mg, '');
We can use replace() method to remove the unwanted string in a string
Example:
var str = '<pre>I'm big fan of Stackoverflow</pre>'
str.replace(/<pre>/g, '').replace(/<\/pre>/g, '')
console.log(str)
output:
Check rules on RULES blotter

Categories

Resources