How to substring in jquery - javascript

How can I use jquery on the client side to substring "nameGorge" and remove "name" so it outputs just "Gorge"?
var name = "nameGorge"; //output Gorge

No jQuery needed! Just use the substring method:
var gorge = name.substring(4);
Or if the text you want to remove isn't static:
var name = 'nameGorge';
var toRemove = 'name';
var gorge = name.replace(toRemove,'');

Using .split(). (Second version uses .slice() and .join() on the Array.)
var result = name.split('name')[1];
var result = name.split('name').slice( 1 ).join(''); // May be a little safer
Using .replace().
var result = name.replace('name','');
Using .slice() on a String.
var result = name.slice( 4 );

Standard javascript will do that using the following syntax:
string.substring(from, to)
var name = "nameGorge";
var output = name.substring(4);
Read more here: http://www.w3schools.com/jsref/jsref_substring.asp

That's just plain JavaScript: see substring and substr.

You don't need jquery in order to do that.
var placeHolder="name";
var res=name.substr(name.indexOf(placeHolder) + placeHolder.length);

var name = "nameGorge";
name.match(/[A-Z].*/)[0]

Yes you can, although it relies on Javascript's inherent functionality and not the jQuery library.
http://www.w3schools.com/jsref/jsref_substr.asp
The substr function will allow you to extract certain parts of the string.
Now, if you're looking for a specific string or character to use to find what part of the string to extract, you can make use of the indexOf function as well.
http://www.w3schools.com/jsref/jsref_IndexOf.asp
The question is somewhat vague though; even just link text with 'name' will achieve the desired result. What's the criteria for getting your substring, exactly?

How about the following?
<script charset='utf-8' type='text/javascript'>
jQuery(function($) { var a=$; a.noConflict();
//assumming that you are using an input text
// element with the text "nameGorge"
var itext_target = a("input[type='text']:contains('nameGorge')");
//gives the second part of the split which is 'Gorge'
itext_target.html().split("nameGorge")[1];
...
});
</script>

Related

Find and replace a substring after a word in javascript

I have a string which has email id as plain text in it ,I want to replace the email id in the string with hashed value eg.
var str ="Token=wUFvvW4pLDjO2Kh9BkF6ShNXMpWCAH84RQrF2GMSMvkT9ji1HWER/hPcDzQVZ+eqfBnzltOP0+NJTa/x6+XrKcSR090Jka8Awdj13CiSiD5OXwFbCHzYX0nzwkbWJ3m7zvyvjIWJJZ7L53YRHckAeTzA39UWR53/s8PHyL7hUu8=&ssoComplete=true&userId=testmail5#gmail.com|flca+&siteID=OXchfjbB"
Before storing the above string I want to hash only testmail5#gmail.com which is after userId=. Hence need suggestions to achieve the same.
Using split twice
var str="Token=wUFvvW4pLDjO2Kh9BkF6ShNXMpWCAH84RQrF2GMSMvkT9ji1HWER/hPcDzQVZ+eqfBnzltOP0+NJTa/x6+XrKcSR090Jka8Awdj13CiSiD5OXwFbCHzYX0nzwkbWJ3m7zvyvjIWJJZ7L53YRHckAeTzA39UWR53/s8PHyL7hUu8=&ssoComplete=true&userId=testmail5#gmail.com|flca+&siteID=OXchfjbB"
console.log(str.split('userId=')[1].split('|')[0])
Try this :
str.match(/\userId=(.*?)\|/)[1]
Regex are better to do stuff like that
Quick and dirty way by using URL API in JS.
var data = "Token=wUFvvW4pLDjO2Kh9BkF6ShNXMpWCAH84RQrF2GMSMvkT9ji1HWER/hPcDzQVZ+eqfBnzltOP0+NJTa/x6+XrKcSR090Jka8Awdj13CiSiD5OXwFbCHzYX0nzwkbWJ3m7zvyvjIWJJZ7L53YRHckAeTzA39UWR53/s8PHyL7hUu8=&ssoComplete=true&userId=testmail5#gmail.com|flca+&siteID=OXchfjbB";
var some_hash = "myHashValue";
var data_url = new URL("http://localhost/?"+data); // dirty part
var new_data = data.replace(data_url.searchParams.get("userId").split('|')[0], some_hash);
console.log(new_data);

JavaScript string .replace for URL

I scrape sites for a database with a chrome extension,
need assitance with a JavaScript Clean up function
e.g
https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p
my target output is:
_60789694386.html
everything past .html needs to be removed, but since it is diffrent in each URL - i'm lost
the output is in a .csv file, in which i run a JavaScript to clean up the data.
this.values[8] = this.values[8].replace("https://www.alibaba.com/product-detail/","");
this.values[8] is how i target the column in the script. (Column 8 holds the URL)
Well, you can use split.
var final = this.values[8].split('.html')[0]
split gives you an array of items split by a string, in your case'.html', then you take the first one.
Consider using substr
this.values[8] = this.values[8].substr(0,this.values[8].indexOf('?'))
You can use split method to divide text from ? as in example.
var link = "https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p"
var result = link.split('?')[0].replace("https://www.alibaba.com/product-detail/","");
console.log(result);
Not sure i understood your problem, but try this
var s = 'https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p'
s = s.substring(0, s.indexOf('?'));
console.log( s );
For when you don't care about readability...
this.values[8] = new URL(this.values[8]).pathname.split("/").pop().replace(".html","");
Alternate, without using split
var link = "https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p"
var result = link.replace('https://www.alibaba.com/product-detail/', '').replace(/\?.*$/, '');
console.log(result);
You can use the regex to get it done. As of my knowledge you do something like:
var v = "https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p"
result = (v.match(/[^\/]+$/)[0]);
result = result.substring(0,result.indexOf('?'));
console.log(result); // will return _60789694386.html

Replace a word in a string using JQuery

I've tried using replaceAll and replaceWith and they don't seem to work
for example, string
"~/Foo.aspx?fn=/image.jpg&p=True"
I want to do is replace p=True with p=False
var previewSource = "~/Foo.aspx?fn/image.jpg&p=True"
var loadedSource = $(previewSource).replaceAll("p=True").replaceWith("p=False");// This is one of the things I have tried.
You can use pure Javscript here:
var previewSource = '~Foo.aspx?fn/image.jpg&p=True';
var loadedSource = previewSource.replace("p=True", "p=False");
How about:
var previewSource = "~Foo.aspx?fn/image.jpg&p=True";
var loadedSource = previewSource.replace(/p=true/i, 'p=False'); // This is one of the things I have tried.
P.S.
Since the value of previewSource is string, you need to wrap them in quotes. Then use simple javascript to replace.

Array.shift() and modify value in a single line?

This Javascript code removes the first file name from a file list and then removes its extension:
var fileNoExt = filelist.shift();
fileNoExt = fileNoExt.substr(0, fileNoExt.lastIndexOf('.'));
I'm curious - is it possible to turn this code into a one-liner?
How about using a regex?
If you want to enforce an extension after the ., use
var fileNoExt = filelist.shift().replace(/\.[^.]+$/, '');
otherwise, use
var fileNoExt = filelist.shift().replace(/\.[^.]*$/, '');
The second one matches my_crazy_file. and my_crazy_file.extension while the first only matches my_crazy_file.extension.
Here's a one-liner:
var filelist = ['file.name.ext', 'some.another.string']
filelist.shift().split('.').slice(0, -1).join('.') // 'file.name'
"is it possible to turn this code into a one-liner?"
Yes,
var fileNoExt = filelist[0].substr(0, filelist.shift().lastIndexOf('.'));
but why? It's clearer on two lines.

find and replace strings in jquery

$('img').click(function(){
var add_to_list = $(this);
// database query for element
});
Currently add_to_list is getting the value 'images/image.jpg'. I want to replace the 'image/' to nothing so I only get the name of the picture (with or without the extension). How can I do this? I couldn't find anything. Also please provide me with further reading on string manipulation please.
Have you tried javascript replace function ?
You should modify your code to something like this:
$('img').click(function(){
var add_to_list = $(this).attr('src').replace('images/', '');
// database query for element
});
use
add_to_list.substring(7);
This will get you the string after the 7th character. If there might be longer paths, you can split() into an array and get the last part of the path using pop().
add_to_list.split("/").pop();
substring
split
pop
This tutorial explains many of the string manipulation methods seen in the answers here.
$('img').click(function(){
var add_to_list = $(this).attr('src').replace('image/', '');
// database query for element
});
var pieces = add_to_list.split('/');
var filename = pieces[pieces.length-1];

Categories