Cutting the String from an input after a certain value with AngularJS - javascript

I am trying to get a value from an input (type = text) and with ngChange I want to write a function so that a link like
https://www.youtube.com/user/testbecomes only user/test
or twitter.com/SomeOne ---> Someone
How am I suppose to do that? I tried substring method but It didnt work fine for me
update : it worked with following code
$scope.cutString = function (link){
var s = link;
s = s.substring(s.indexOf("/")+1,s.length);
console.log(s);
this.link = s;
$scope.publisher.facebook = s ;
};
HTML Part ;
<input type="text" class="form-control" id="facebook" data-ng-model="publisher.facebook"
ng-change="cutString(publisher.facebook)">
but now the problem is I have the same for Facebook, Twitter and Youtube, how can I manage them all in one method?
PS: I cant upload whole code since its against my work contract.

You could:
function getUserPath(link) {
var regex = /^((http[s]?|ftp):\/)?\/?([^:\/s]+)\//;
return link.replace(regex, "");
}
And then call getUserPath wherever you need that logic.
With this RegExp you will always get the path after the first "/" that is not part of the "http://".

Related

Regex for finding link

I have an issue related to finding a regex for the link with some conditions. Here is the scenario:
I have created utils.ts it's a typescript. basically, it will take an API response as an input and return the formatted HTML supported text, like bold text, email, Images, Links.
So let's take one scenario which I am facing.
as a return of the utils.ts file, I am getting this.
https://www.google.com Click here
(Note: normal links and 'a' tag links can occure in any order)
from the above text, as you can see this part Click here is already in HTML supported method.
So I will get the following output on GUI
https://www.google.com Click here
so from this point, I want a regex which can format https://www.google.com but it must not manipulate Click here as it is already formated.
Here I also want to format https:///www.google.com as follow
Google
The main problem I am facing is when I am replacing the string with 'https://..' with tags it will also replace the links inside 'href' like this
Google Google">Click me</a>
Which is what I don't want.
Please share your thought on this.
Thank you
Not yet formatted links can be found using alternations. The idea is - if a link is formatted it's not captured to a group (don't be confused that the regex still finds something - you should only look at Group 1). Otherwise, the link is captured to a group.
The regex below is really simple, just to explain the idea. You might want to update it with a better URL search pattern.
demo
(?:href="https?\S+")|(https?\S+)
If I understood correctly, you want to extract from the text those web addresses that appear in the text and are not links. If so check out the following javascript:
//the data:
var txt1='https://www.google.com Click here http://other.domain.com';
// strip html tags
String.prototype.stripHTML = function () {
var reTag = /<(?:.|\s)*?>/g;
return this.replace(reTag, " ");
};
var txt2=txt1.stripHTML();
//console.log(txt2);
//split tokens
var regex1 = /\s/;
var tokens = txt2.split(regex1);
//console.log(tokens);
//build an address table
regex2=/^https?:\/\/.*/;
var i=0, j=0;
var addresses=[];
for (i in tokens) {
if (regex2.test(tokens[i])) {
addresses[j] = tokens[i];
j++;
}
i++;
}
console.log(addresses);

Replace part of a string with another string javascript

what I have is 3 text boxes. The first one a user enters a string. The second box they enter part of the first string they want to replace. The third text box is the string that is to do the replacing.
I'm trying to use the replace() method but I dont think Im using it right or i should be using something else.
html:
<form>
Enter a string:<input type="text" id="user_string"><br>
Enter portion of previous string to be replaced: <input type="text" id="replace_string"><br>
Enter new string: <input type="text" id="add_string"><br>
<input type="button" value="Execute" onclick="BaitAndSwitch()"><br>
Result: <input type="text" id="req_4_results"><br>
</form>
Javascript:
function BaitAndSwitch(){
// create variables for the user entered data
var UserString = document.getElementById("user_string").value;
var ReplaceString = document.getElementById("replace_string").value;
var AddString = document.getElementById("add_string").value;
var Results = UserString.replace(ReplaceString, Addstring);
if (UserString.indexOf(ReplaceString) > -1) {
Document.getElementById("req_4_results").value = Results;
}
else{
alert("Something went wrong! Please check the data you entered.")
}
}
I know I'm doing something wrong. Maybe the use of variables in the .replace() method? Or maybe the if... using indexOf line?
I was essentially trying to set it up where it would check UserString with the value of ReplaceString and if it matched, it would then execute the replace() method and show results to the given HTML element. Else if the ReplaceString didn't match any thing from UserString, it would alert the user something was wrong and to check it.
JavaScript is cAsE SeNsItIvE. Please note that Document is not the same as the document object. Please use the below line:
document.getElementById("req_4_results").value = Results;
Oh and yes, as pointed out by blex, you have another typo too:
var Results = UserString.replace(ReplaceString, Addstring);
//-------------------------------------------------^ should be S
More Info: In the console, if you try both, see the result you get:
typeof Document
// "function"
typeof document
// "object"
On a side note, please do not use such Naming Conventions. Looks like you are migrating from Visual Basic.
Note that the replace() method does not modify the string that you call it on.
In your line of code:
var Results = UserString.replace(ReplaceString, Addstring);
The value of UserString will not changed as a result of having called replace() on it.
In your conditional statement:
UserString.indexOf(ReplaceString) > -1
If it is true, it means that UserString still contains at least one instance of ReplaceString within it.
That makes sense, because you wouldn't have modified UserString yet. If you want to make sure that Results no longer has any occurrence of ReplaceString, then you want to throw an error only if the following condition is true:
Results.indexOf(ReplaceString) > -1

JavaScript - find text in URL by position

This should be pretty easy but I'm struggling.
I have a button that fires a function. I want an alert to fire as well that tells me which page the user was on.
www.whatever.com/thispage1/whatever
www.whatever.com/thispage2/whatever
www.whatever.com/thispage3/whatever
So after my button is clicked, I want an alert that reads back "thispage1" or "thispage2" etc. I do not want the entire URL fed back to me. Is there a way to find text in a url based on its position or number of characters before it starts?
Look at window.location.pathname and use str.slice to extract the bit you want, with str.indexOf to find the indices to start/end at
var top_dir = window.location.pathname.slice(
1,
window.location.pathname.indexOf('/', 1)
);
Maybe this will help you get started. Key players here are window.location.pathname and string.split()
var returnPage = function() {
var urlString = window.location.pathname;
var stringArray = urlString.split("/");
return stringArray[0]; // number == whichever piece of the array you want to get
};
function myFunction() {
alert(returnPage());
}

Why missing one character from my regex?

I have a very good regex function which call in here:
<input onkeyup="vimeo();">
But the problem is, when the user paste a link in to the input, he get this link:
//player.imeo.com/video/VIDEOID
You see? Missing "v" from vimeo and I can't pass on this problem.
If I delete the "/" character before of "v" I get repeated value, for example:
//player.player.player.player.player.player.player.player.vimeo.com/video/VIDEOID
My replace script looks like this:
var vimeo = function(){
var str2;
$('#url').keyup(function(){
str2 = $(this).val();
$(this).val(str2.replace(/(?:http:\/\/)?(?:www\.)?(?:vimeo\.com)\/(.+)/g, '\/\/player/\.\vimeo\.\com\/video/$1'));
});
};
How can I fix missing "v" without repeat any value?
Update:
Demo link is here:
http://neocsatblog.mblx.hu/addvideos/
The problem is your replacement string. You don't need to escape any characters. The second argument of the replace method takes a string, not another regular expression.
'\/\/player/\.\vimeo\.\com\/video/$1'
You can just do this:
'//player.vimeo.com/video/$1'
I am not sure why you are using a keyup event on your input as well as your url element, however.
I changed your function a bit and it works for me.
EDIT
Since you want to only use one field, you'll need to use onchange to format the url once the user is done editing. I've changed the function to reflect this change. Notice, you don't even need jQuery anymore.
var vimeo = function(elem) {
var str2 = elem.value;
elem.value = str2.replace(/(?:http:\/\/)?(?:www\.)?(?:vimeo\.com)\/(.+)/g, '//player.vimeo.com/video/$1');
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input onchange="vimeo(this);">

Converting Javascript hashtag

What I'm trying to do is fetch a single piece of a string without using the hashtag element in the url. I already have a functioning code but it needs altering. So, how do I fetch any part of the url after ?.
Say I have ?fx=shipment+toys/fish-fix-fx/ as my url string; I want the button to show if shipment or fish or fx was my choice of selections for example.
Buttons showing with hastag: http://jsfiddle.net/66kCf/2/show/#iphone
Original JSFiddle (buttons not showing): http://jsfiddle.net/66kCf/2/
I want the iPhone buttons to show if fix was my choice: http://jsfiddle.net/66kCf/2/show/?fx=shipment+toys/fish-fix-fx/
try doing it with .split() and.match() like this...
var keys = window.location.href.split('?');
if (keys[1].match(/(fix|fish|fx)/))
{
$("#linkdiv").append(nextLink);
$("#linkdiv1").append(nextLink);
$("#linkdiv2").append(nextLink);
}
demo button showing : http://jsfiddle.net/LbKmf/show/?fx=shipment+toys/fish-fix-fx/
demo button not showing: http://jsfiddle.net/LbKmf/show/?reigel
Is this what your looking for:
"?fx=shipment+toys/fish-fix-fx/".split(/[\?=+\/-]/g);
window.location.search and split into array for comparisons
explained in How can I get a specific parameter from location.search?
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
Generally, Javascript doesn't have a built-in functionality for query string parameters. You can use string manipulation on window.location.search to get your parameters out of the URL string. Note that location.search includes the ? character too.
Something like this should do:
var queryString = function () {
// Anonymous function - executed immediately
// get rid of the '?' char
var str = "?fx=shipment+toys/fish-fix-fx/";
var query = str.substring(str.lastIndexOf('=')+1,str.indexOf('/'));
var vars = query.split("+");
for (var i=0;i<vars.length;i++){
console.log(vars[i]);
}
return vars;
} ();

Categories

Resources