Javascript - Make specific text a link [duplicate] - javascript

This question already has answers here:
Detect URLs in text with JavaScript
(15 answers)
Closed 4 years ago.
I'm looking at a 'to do' list application that uses JavaScript.
One of the functions converts text in to a hyperlink when https, https or ftp is present.
I'd like to expand this so if my text contains # followed by any 5 digit number, that becomes a link as well. The URL should be http://192.168.0.1/localsite/testschool/search.php?id=ID
where ID is the # and 5 digit number.
This is the current Javascript:
function prepareHtml(s)
{
// make URLs clickable
s = s.replace(/(^|\s|>)(www\.([\w\#$%&~\/.\-\+;:=,\?\[\]#]+?))(,|\.|:|)?(?=\s|"|<|>|\"|<|>|$)/gi, '$1$2$4');
return s.replace(/(^|\s|>)((?:http|https|ftp):\/\/([\w\#$%&~\/.\-\+;:=,\?\[\]#]+?))(,|\.|:|)?(?=\s|"|<|>|\"|<|>|$)/ig, '$1$2$4');
};
called using prepareHtml(item.title)
Any idea how I can do this ?
I've worked out regex to match the # and 5 digits is ^#([0-9]{5}) but I'm not sure how to implement this in the function.
Thanks

Looks to me that the pattern & replace string can be simplified a bit.
function urls2links(s)
{
return s.replace(/(^|[\s>])(www\.)/gi, '$1http://$2')
.replace(/\b(((https?|ftps?):\/{2})(\S+?))(?="|<|>|[\s<>\"]|$)/ig, '$1');
};
var str = 'blah http://192.168.0.1/localsite/testschool/search.php?id=#12345 \nblah www.foo.com/bar/" blah';
console.log('--\n-- BEFORE\n--');
console.log(str);
console.log('--\n-- AFTER\n--');
console.log(urls2links(str));
Although I'm not too sure about needing to include the character entities |"|<|> in the lookahead.
But I'm guessing you also deal with encoded strings.

Related

Remove empty characters, blank characters, invisible characters in jQuery [duplicate]

This question already has answers here:
Remove not alphanumeric characters from string
(10 answers)
Regular expression to remove anything but alphabets and '[single quote]
(1 answer)
javascript regex to return letters only
(6 answers)
Ignoring invisible characters in RegEx
(2 answers)
Closed 2 years ago.
I am performing a validation in html text box which should pass only alphabets(a-z/A-Z) and few special characters like (*,& etc..). Otherwise it should show error some error.
I had written a JavaScript function which does the same.
function removeInvalidCharacters(selectedElement) {
if (selectedElement && typeof selectedElement.val() !== typeof undefined && selectedElement.val() != "") {
selectedElement.val(selectedElement.val().replace(/[\u0000-\u001F]|[\u007F-\u00A0]/g, "").replace(/\\f/g, "").replace(/%/g,""));
}
}
I am filtering selectedElement before passing to the function removeInvalidCharacters.
$("#name").val(toASCII($("#name").val()));
var selectedElement = $("#name").val();
But now I am facing a scenario in which empty characters, blank characters, invisible characters and whitespace characters are bypassing my regex. I could see some invisible characters are present in my name field. I want to replace these characters.
In further investigation I could found that Invisible characters - ASCII
characters mentioned in this link are the culprits. I need to have a regex to catch them and replace them.
Eg: AAAAAAAAAAAA‎AAAAAAAAAAA is the value in text field. Now if we check $("#name").val().length, it gives 24 ,even though we could see only 23 characters. I need to remove that hidden character.
Please help me with this scenario. Hope my query is clear
UPDATE:
var result = selectedElement.replace(/[\u200B-\u200D\uFEFF]/g, ''); fixed my problem.
Thank you all for the support.
If you want to allow only (a-z/A-Z) like you mention, try this:
str = str.replace(/[^a-zA-Z]/g, '');
Include the chars you want to keep instead of the ones you do not want, since that list may be incomplete
Otherwise look here: Remove zero-width space characters from a JavaScript string
const val = `AAAAAAAAAAAA‎AAAA**AAAAAAA`;
const cleaned = val.replace(/[^A-Za-z*]/g,"");
console.log(val.length,cleaned.length);

Getting a true or false reply to a Regex match? [duplicate]

This question already has answers here:
Return true/false for a matched/not matched regex
(5 answers)
Closed 3 years ago.
I'm trying to match an entire string against a regex formula. This is for validating if a phone number field is likely correct (just based on allowed characters, anyone can make up an number). I've played with Regex before but never truly understood the nuances that make it powerful.
Below I have my dummy phone number and I have the regex I'm using. As you can see I'm simply comparing the length of the match vs the length of the string and if they match the number must be valid.
Is there a way to get a simple true/false reply from a Regex check on an entire string?
var num = '+1 (888) 456-7896';
var regex = /[0-9+ ()-]*$/;
var found = num.match(regex);
console.log(found[0].length);
console.log(num.length);
You can use test()
var found = regex.test(num);

How do I insert something at a specific character with Regex in Javascript [duplicate]

This question already has answers here:
Simple javascript find and replace
(6 answers)
Closed 5 years ago.
I have string "foo?bar" and I want to insert "baz" at the ?. This ? may not always be at the 3 index, so I always want to insert something string at this ? char to get "foo?bazbar"
The String.protype.replace method is perfect for this.
Example
let result = "foo?bar".replace(/\?/, '?baz');
alert(result);
I have used a RegEx in this example as requested, although you could do it without RegEx too.
Additional notes.
If you expect the string "foo?bar?boo" to result in "foo?bazbar?boo" the above code works as-is
If you expect the string "foo?bar?boo" to result in "foo?bazbar?bazboo" you can change the call to .replace(/\?/g, '?baz')
You don't need a regular expression, since you're not matching a pattern, just ordinary string replacement.
string = 'foo?bar';
newString = string.replace('?', '?baz');
console.log(newString);

javascript - Regex make string uppercase [duplicate]

This question already has answers here:
Replace a Regex capture group with uppercase in Javascript
(7 answers)
Closed 5 years ago.
I wonder if there is a way to make a string uppercase using regex only in JS.
The thing is that I am giving my users a string transformation system.
The user supply me with three parameters : original text, replace regex, subtitution regex.
for example:
original : 'stackoverflow'
replace : /([a-z])(.*)/g
subtitution : $1
Result : 's'
I want to give them the abilitty to set the entire string to uppercase. I've noticed in some other SO questions that there are systems that allows that. for example in sublime text you can do '/\U$1/' to set the entire string to uppercase.
Notice: I cannot use toUpperCase or toLowerCase in any way
Javascript has an inbuilt uppercasing method
var str = "Hello World!";
var res = str.toUpperCase();
The result of res will be:
HELLO WORLD!

How do I properly use RegExp in JavaScript and PHP? [duplicate]

This question already has an answer here:
Learning Regular Expressions [closed]
(1 answer)
Closed 6 years ago.
How do I properly use RegExp?
var text = "here come dat boi o shit waddup";
var exmaple = /[a-zA-Z0-9 ]/; // allowes a-zA-Z0-9 and whitespaces but nothing else right?
example.test(test); // would return true right?
text = "%coconut$§=";
example.test(text); // would return false right?
//I know this is very basic - I started learnig all this about week ago
Are JS RegExp's the same as PHP RegExp's?
How do I define banned characters instead of defining allowed characters?
How do I make it so that the var text has to contain 3 (or more) numbers/letters?
How do I include / or ",'$ etc. in my pattern?
No.
Use ^ character (i.e. [^abc] will exclude a, b and c)
Use [A-Za-z]{3} for letters and \d{3} for digits. If you want 3 or more, use \d{3,}
Use escape character (\/, \', \", '\$')

Categories

Resources