How can I find a specific string and replace based on character? - javascript

I'm trying to find a specific character, for example '?' and then remove all text behind the char until I hit a whitespace.
So that:
var string = '?What is going on here?';
Then the new string would be: 'is going on here';
I have been using this:
var mod_content = content.substring(content.indexOf(' ') + 1);
But this is not valid anymore, since the specific string also can be in the middle of a string also.
I haven't really tried anything but this. I have no idea at all how to do it.

use:
string = string.replace(/\?\S*\s+/g, '');
Update:
If want to remove the last ? too, then use
string = string.replace(/\?\S*\s*/g, '');

var firstBit = str.split("?");
var bityouWant = firstBit.substring(firstBit.indexOf(' ') + 1);

Related

how to replace words in string using javascript?

i have a string,
mystr = 'public\uploads\file-1490095922739.jpg';
i want to replace
public\uploads
with " ", so that i just want to extract only file name ie
file-1490095922739.jpg
or like,
\uploads\file-1490095922739.jpg
how can i do this, is there any methods for this in js or can we do it by replace method.
i am performing the following steps,
var imagepath1;
var imagepath = 'public\uploads\file-1490095922739.jpg';
unwantedChar = 'public|uploads';
regExp = new RegExp(unwantedChar , 'gi');
imagepath = imagepath.replace(regExp , '');
imagepath1 = imagepath;
$scope.model.imagepath = imagepath1.replace(/\\/g, "");
please suggest me optimized method.
var input = "public\\uploads\\file-1490095922739.jpg";
var result = input.replace("public\\uploads\\", "");
This is what you're looking for, no need for fancy regexs :). More information about replace can be found here.
Maybe I don't understand the issue - but wouldn't this work?
var mystr = 'public\uploads\file-1490095922739.jpg';
var filename = mystr.replace('public\uploads', '');
If you want to get the part of the string after the last backslash character, you can use this:
var filename = mystr.substr(mystr.lastIndexOf('\\') + 1);
Also note that you need to escape the backslash characters in your test string:
var mystr = 'public\\uploads\\file-1490095922739.jpg';
What about just doing:
var imagepath = 'public\\uploads\\file-1490095922739.jpg';
$scope.model.imagepath = imagepath.replace('public\\uploads\\', '');
instead of using a bunch of unnecessary variables?
This way you're getting the file path, removing public\uploads\ and then setting the file path to $scope.model.imagepath
Note that this will only work if the image file path always matches 'public\uploads\*FILENAME*'.
var url = '/anysource/anypath/myfilename.gif';
var filename = url.slice(url.lastIndexOf('/')+1,url.length);
Search for the last forward slash, and slice the string (+1 because you don't want the slash), with the length of the string to get the filename. This way, you don't have to worry about the path is at all times.

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";

Trim a variable's value until it reaches to a certain character

so my idea is like this..
var songList = ["1. somesong.mid","13. abcdef.mid","153. acde.mid"];
var newString = myString.substr(4); // i want this to dynamically trim the numbers till it has reached the .
// but i wanted the 1. 13. 153. and so on removed.
// i have more value's in my array with different 'numbers' in the beginning
so im having trouble with this can anyone help me find a more simple solution which dynamically chop's down the first character's till the '.' ?
You can do something like
var songList = ["1. somesong.mid","13. abcdef.mid","153. acde.mid"];
songList.forEach(function(value, i){
songList[i] = value.replace(/\d+\./, ''); //value.substr(value.indexOf('.') + 1)
});
Demo: Fiddle
You can use the string .match() method to extract the part up to and including the first . as follows:
var newString = myString.match(/[^.]*./)[0];
That assumes that there will be a match. If you need to allow for no match occurring then perhaps:
var newString = (myString.match(/[^.]*./) || [myString])[0];
If you're saying you want to remove the numbers and keep the rest of the string, then a simple .replace() will do it:
var newString = myString.replace(/^[^.]*. */, "");

append single quotes to characters

I have a string like
var test = "1,2,3,4";
I need to append single quotes (' ') to all characters of this string like this:
var NewString = " '1','2','3','4' ";
Please give me any suggestion.
First, I would split the string into an array, which then makes it easier to manipulate into any form you want. Then, you can glue it back together again with whatever glue you want (in this case ','). The only remaining thing to do is ensure that it starts and ends correctly (in this case with an ').
var test = "1,2,3,4";
var formatted = "'" + test.split(',').join("','") + "'"
var newString = test.replace(/(\d)/g, "'$1'");
JS Fiddle demo (please open your JavaScript/developer console to see the output).
For multiple-digits:
var newString = test.replace(/(\d+)/g, "'$1'");
JS Fiddle demo.
References:
Regular expressions (at the Mozilla Developer Network).
Even simpler
test = test.replace(/\b/g, "'");
A short and specific solution:
"1,2,3,4".replace(/(\d+)/g, "'$1'")
A more complete solution which quotes any element and also handles space around the separator:
"1,2,3,4".split(/\s*,\s*/).map(function (x) { return "'" + x + "'"; }).join(",")
Using regex:
var NewString = test.replace(/(\d+)/g, "'$1'");
A string is actually like an array, so you can do something like this:
var test = "1,2,3,4";
var testOut = "";
for(var i; i<test.length; i++){
testOut += "'" + test[i] + "'";
}
That's of course answering your question quite literally by appending to each and every character (including any commas etc.).
If you needed to keep the commas, just use test.split(',') beforehand and add it after.
(Further explanation upon request if that's not clear).

What regex can I use to extract the URL from an HTTP <a> element?

Here is the Original string :
var str = " a vartiable";
and I need this part:
str = "https://sjobs.brassring.com/1033/ASP/TG/cim_jobdetail.asp?SID=^cJgiKPhGBHyn5VRSb9gbJg0K2T88FrLqHyAtd6hd5pJ7JeXxNyq0VatKCq3jYWp/&jobId=385594&type=hotjobs&JobReqLang=141&JobSiteId=5239&JobSiteInfo=385594_5239&GQId=0";
In other words, I need to remove the tag <a> and the document.href value
Thanks guys.
How about:
var str = " a vartiable";
str.replace(/^<a href="(https.*?)cim_home\.asp.*?'(cim_jobdetail\.asp.*)'.*$/, "$1$2");
produces:
"https://sjobs.brassring.com/1033/ASP/TG/cim_jobdetail.asp?SID=^cJgiKPhGBHyn5VRSb9gbJg0K2T88FrLqHyAtd6hd5pJ7JeXxNyq0VatKCq3jYWp/&jobId=385594&type=hotjobs&JobReqLang=141&JobSiteId=5239&JobSiteInfo=385594_5239&GQId=0"
Something simple like the following should work...
href="(.*?)"
here's the code u want:
var str = ' a vartiable'
var url = /\"(.*?)\"/str
that's how you match, here's how you strip it out:
str.replace(/\"(.*?)\"/, "$1");
the \"(.*?)\" gives the first minimal set of characters between two " characters the id of $1 then the second argument to the replace function tells it to replace the whole string with what's contained in $1
Also, if you use jQuery, this becomes pretty trivial:
var url = $("a").attr("href");

Categories

Resources