How to replace last matched character in string using javascript - javascript

i want to replace last input character from keyboard to ''
My String Input are
sample string
"<p><strong>abscd sample text</strong></p>"
"<p>abscd sample text!</p>"
My last character is dynamic that can be any thing between
a to z, A to Z, 0 to 9, any special characters([~ / < > & ( . ] ).
So i need to replace just that character
for example in Sample 1 i need to replace "t" and in sample 2 in need to replace "!"
I tried below code. but it id not worked for me
var replace = '/'+somechar+'$/';
Any way to do it?

Step one
to replace the a character in a string, use replace() function of javaScript. Here is the MDN specification:
Returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.
Step two
you need to location the character to be replaced through regular expression. You want to replace the last character of a string and this could be expressed as /(.+)(.)$/. . stands for any character, + means more than one character. Here (.+) matches all the character before the last one. (.) matches the last character.
What you want to replace is the one inside the second brackets. Thus you use the same string matched in the first bracket with $1 and replace whatever after it.
Here is the code to realize your intention:
text = 'abscd sample text';
text.replace(/(.+)(.)$/, '$1!');

Do you really need to use regular expressions? How about str = str.slice(0, -1); ? This will remove the last character.
If you need to replace a specific character, do it like this:
var replace = new RegExp(somechar + '$');
str = str.replace(replace, '');
You cannot use slashes in a string to construct a RegEx. This is different from PHP, for example.

I dont really understand which character you want to replace to what, but i think, you should use replace() function in JS: http://w3schools.com/jsref/jsref_replace.asp
string.replace(regexp/substr,newstring)
This means all keyboard character:
[\t\n ./<>?;:"'`!##$%^&*()[]{}_+=-|\\]
And this way you can replace all keyboard character before < mark to ""
string.replace("[a-zA-Z0-9\t\n ./<>?;:"'`!##$%^&*()[]{}_+=-|\\]<","<")

Related

regex custom lenght but no whitespace allowed [duplicate]

I have a username field in my form. I want to not allow spaces anywhere in the string. I have used this regex:
var regexp = /^\S/;
This works for me if there are spaces between the characters. That is if username is ABC DEF. It doesn't work if a space is in the beginning, e.g. <space><space>ABC. What should the regex be?
While you have specified the start anchor and the first letter, you have not done anything for the rest of the string. You seem to want repetition of that character class until the end of the string:
var regexp = /^\S*$/; // a string consisting only of non-whitespaces
Use + plus sign (Match one or more of the previous items),
var regexp = /^\S+$/
If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()
Than Below string will work
'^\\S*$'
It's same regex #Bergi mentioned just the string version for new RegExp constructor
This will help to find the spaces in the beginning, middle and ending:
var regexp = /\s/g
This one will only match the input field or string if there are no spaces. If there are any spaces, it will not match at all.
/^([A-z0-9!##$%^&*().,<>{}[\]<>?_=+\-|;:\'\"\/])*[^\s]\1*$/
Matches from the beginning of the line to the end. Accepts alphanumeric characters, numbers, and most special characters.
If you want just alphanumeric characters then change what is in the [] like so:
/^([A-z])*[^\s]\1*$/

Extract text from document title

I try to extract all text from document title before it gets to closest "|" or "-" or "/" . I assume i have to write something like this but im not good at regex.
var docTitle = document.title();
docTitle.match(regex);
Can someone help me with correct regex or suggest perhaps a better solution to achieve desired effect ?
Thank you !
Use var shortTitle = document.title.split(/[|\/-]/,1)[0];
The split function divides a string into an array based on a separator.
You can pass a Regular Expression object into the split function if the separator is a pattern and not constant.
The regular expression is [|/-] meaning any |, /, or -. The / needed to be escaped with a \ in JavaScript because / is also the character that delimits Regular Expression literals.
The first element of the split array ([0]) will be the document title before the first occurrence of any of those separator characters.
It will be the only element in the array, because we told the split function to stop after the first occurrence.
If the document title contains no matching characters to split on, the split function returns the whole string in the first array element, anyway.

Regex match for a specific pattern excluding a specific pattern

I have sample string as :
'&label=20:01:27&tooltext=abc\&|\|cba&value=6|59|58|89&color=ff0000|00ffff'
'&label=20:01:27&tooltext=abc\&|\|cba&value=6|59|58|89'
My objective is to select the text from 'tooltext=' till the first occurrence of '&' which is not preceded by \\. I'm using the following regex :
/(tooltext=)(.*)([^\\])(&)/
and the .match() function.
It is working fine for the second string but for the first string it is selecting upto the last occurrence of '&' not preceded by \\.
var a = '&label=20:01:27&tooltext=abc\&|\|cba&value=6|59|58|89&color=ff0000|00ffff',
b = a.match(/(tooltext=)(.*)([^\\])(&)(.*[^\\]&)?/i)
result,
b = ["tooltext=abc\&|\|cba&value=40|84|40|62&", "tooltext=", "abc\&|\|cba&value=40|84|40|6", "2", "&"]
But what i need is:
b = ["tooltext=abc&||cba&", "tooltext=", "abc&||cb", "a", "&"]
I think you can use a regex like this:
/tooltext=(.*?\\&)*.*?&/
[Regex Demo]
and to always found a non-escaped &:
/tooltext=(.*?\\&)*.*?[^\\]&/
It looks like your regex is matching all the way to the last & instead of the first one without a backslash in front of it. Try adding the ? operator to make it match as small as possible like so:
/(tooltext=)(.*?)([^\\])(&)/
And if you just want the text between tooltext= and &, try this to make it return the important part as the matched group:
/tooltext=(.*?[^\\])&/

match a string not after another string

This
var re = /[^<a]b/;
var str = "<a>b";
console.log(str.match(re)[0]);
matches >b.
However, I don't understand why this pattern /[^<a>]b/ doesn't match anything. I want to capture only the "b".
The reason why /[^<a>]b/ doesn't do anything is that you are ignoring <, a, and > as individual characters, so rewriting it as /[^><a]b/ would do the same thing. I doubt this is what you want, though. Try the following:
var re = /<a>(b)/;
var str = "<a>b";
console.log(str.match(re)[1]);
This regex looks for a string that looks like <a>b first, but it captures the b with the parentheses. To access the b, simply use [1] when you call .match instead of [0], which would return the entire string (<a>b).
What you're using here is a match for a b preceded by any character that is not listed in the group. The syntax [^a-z+-] where the a-z+- is a range of characters (in this case, the range of the lowercase Latin letters, a plus sign and a minus sign). So, what your regex pattern matches is any b preceded by a character that is NOT < or a. Since > doesn't fall in that range, it matches it.
The range selector basically works the same as a list of characters that are seperated by OR pipes: [abcd] matches the same as (a|b|c|d). Range selectors just have an extra functionality of also matching that same string via [a-d], using a dash in between character ranges. Putting a ^ at the start of a range automatically turns this positive range selector into a negative one, so it will match anything BUT the characters in that range.
What you are looking for is a negative lookahead. Those can exclude something from matching longer strings. Those work in this format: (?!do not match) where do not match uses the normal regex syntax. In this case, you want to test if the preceding string does not match <a>, so just use:
(?!<a>)(.{3}|^.{0,2})b
That will match the b when it is either preceded by three characters that are not <a>, or by fewer characters that are at the start of the line.
PS: what you are probably looking for is the "negative lookbehind", which sadly isn't available in JavaScript regular expressions. The way that would work is (?<!<a>)b in other languages. Because JavaScript doesn't have negative lookbehinds, you'll have to use this alternative regex.
you could write a pattern to match anchor tag and then replace it with empty string
var str = "<a>b</a>";
str = str.replace(/((<a[\w\s=\[\]\'\"\-]*>)|</a>)/gi,'')
this will replace the following strings with 'b'
<a>b</a>
<a class='link-l3'>b</a>
to better get familiar with regEx patterns you may find this website very useful regExPal
Your code :
var re = /[^<a>]b/;
var str = "<a>b";
console.log(str.match(re));
Why [^<a>]b is not matching with anything ?
The meaning of [^<a>]b is any character except < or a or > then b .
Hear b is followed by > , so it will not match .
If you want to match b , then you need to give like this :
var re = /(?:[\<a\>])(b)/;
var str = "<a>b";
console.log(str.match(re)[1]);
DEMO And EXPLANATION

JS & Regex: how to replace punctuation pattern properly?

Given an input text such where all spaces are replaced by n _ :
Hello_world_?. Hello_other_sentenc3___. World___________.
I want to keep the _ between words, but I want to stick each punctuation back to the last word of a sentence without any space between last word and punctuation. I want to use the the punctuation as pivot of my regex.
I wrote the following JS-Regex:
str = str.replace(/(_| )*([:punct:])*( |_)/g, "$2$3");
This fails, since it returns :
Hello_world_?. Hello_other_sentenc3_. World_._
Why it doesn't works ? How to delete all "_" between the last word and the punctuation ?
http://jsfiddle.net/9c4z5/
Try the following regex, which makes use of a positive lookahead:
str = str.replace(/_+(?=\.)/g, "");
It replaces all underscores which are immediately followed by a punctuation character with the empty string, thus removing them.
If you want to match other punctuation characters than just the period, replace the \. part with an appropriate character class.
JavaScript doesn't have :punct: in its regex implementation. I believe you'd have to list out the punctuation characters you care about, perhaps something like this:
str = str.replace(/(_| )+([.,?])/g, "$2");
That is, replace any group of _ or space that is immediately followed by punctation with just the punctuation.
Demo: http://jsfiddle.net/9c4z5/2/

Categories

Resources