Find and replace string with dot in javascript - javascript

I want to find and replace a part of string if present in string.
String is like '1.png,2.png,3.jpg,4.gif'
I want find 1.png in this string and then replace it if exist with 1.jpg.
I am not able to find it using search() and indexOf() method.
and since i am not able to find it i cannot replace it.
I am trying this way
var str = '1.png'
var new_str = '1.jpg'
var main_str = '1.png,2.png,3.jpg,4.gif';
if(main_str.indexOf(str) > 0){
alert('found')
// now replace it with new_str
}
else{
alert('not found')
}
I have tried following combination but these are not working.
main_str.indexOf('str') > 0
main_str.indexOf(/\str/) > 0
main_str.indexOf(/\"str"/) > 0
main_str.indexOf(str) > 0
Please see and suggest any possible way to do this.
Thanks

The index of 1.png in your string is actually 0, that is why your condition fails. Correct way is to check whether index is not negative, since indexOf returns -1 if substring is not found:
if(main_str.indexOf(str) >= 0){
but even better approach here is to use replace:
main_str.replace(str, new_str)

Since the main_str contains 1.png at index 0, you can never find it with the check main_str.indexOf('str') > 0. Remeber that javascript returns -1 if not found and not zero. So you'll have to update your condition to:
main_str.indexOf('str') != -1

try,
var str="1.png,2.png,3.jpg,4.gif";
var newStr=str.replace(".png",".jpg");

you can use the replace method:
var str = '1.png,2.png,3.jpg,4.gif';
var result=str.replace('1.png','1.jpg')

You can do the replacement using replace :
main_str = main_str.replace(str, new_str)
If you want to replace more than one occurrence, use
main_str = main_str.replace(new RegExp(str,'g'), new_str)
If you want to alert before replacing, do this :
var r = new RegExp(str,'g');
if (main_str.match(r)) {
alert('found')
main_str = main_str.replace(r, new_str)
} else {
alert('not found')
}

you can do this:
var str = "1.png,2.png,3.jpg,4.gif";
var re = /(.png)/i;
var found = str.match(re);
//now ask the user or do whatever else is needed
if (found){
found = confirm("Really overwrite");
}
if (found){
str = str.replace(re, ".jpg");
}
I allow in the string now also upper case or mixed case, like ".Png" or ".PNG"

Related

Unable to get numbers from window.location.search

I am using the following code in my JS file:
var match = window.location.search.match(/(\d*)/);
this.room = (match) ? decodeURIComponent(match) : 0;
And I am trying to just get the numbers from my URL. For example, in www.myurl.com/streams228, I just want to get the 228.
The issue I am getting is it is just returning %2, nothing else, or 0.
Try the following:
var url ="www.myurl.com/streams228"
var match = url.match(/([\d]+)/g);
console.log(match[0]);
Try to match the pathname. The search refers to the query string.
window.location.pathname.match(/(\d*)/)
After using the code above from everyone I did this
var match = window.location.pathname.match(/([\d]+)/g);
this.room = (match && match[0]) ? decodeURIComponent(match[0]) : 0;
and it works perfectly.
Thanks

Javascript regex to replace "split"

I would like to use Javascript Regex instead of split.
Here is the example string:
var str = "123:foo";
The current method calls:
str.split(":")[1]
This will return "foo", but it raises an Error when given a bad string that doesn't have a :.
So this would raise an error:
var str = "fooblah";
In the case of "fooblah" I'd like to just return an empty string.
This should be pretty simple, but went looking for it, and couldn't figure it out. Thank you in advance.
Remove the part up to and including the colon (or the end of the string, if there's no colon):
"123:foo".replace(/.*?(:|$)/, '') // "foo"
"foobar" .replace(/.*?(:|$)/, '') // ""
How this regexp works:
.* Grab everything
? non-greedily
( until we come to
: a colon
| or
$ the end of the string
)
A regex won't help you. Your error likely arises from trying to use undefined later. Instead, check the length of the split first.
var arr = str.split(':');
if (arr.length < 2) {
// Do something to handle a bad string
} else {
var match = arr[1];
...
}
Here's what I've always used, with different variations; this is just a simple version of it:
function split(str, d) {
var op = "";
if(str.indexOf(d) > 0) {
op = str.split(d);
}
return(op);
}
Fairly simple, either returns an array or an empty string.
var str1 = "123:foo", str2 = "fooblah";
var res = function (s) {
return /:/.test(s) && s.replace(/.*(?=:):/, "") || ""
};
console.log(res(str1), res(str2))
Here is a solution using a single regex, with the part you want in the capturing group:
^[^:]*:([^:]+)

javascript get string before a character

I have a string that and I am trying to extract the characters before the quote.
Example is extract the 14 from 14' - €14.99
I am using the follwing code to acheive this.
$menuItem.text().match(/[^']*/)[0]
My problem is that if the string is something like €0.88 I wish to get an empty string returned. However I get back the full string of €0.88.
What I am I doing wrong with the match?
This is the what you should use to split:
string.slice(0, string.indexOf("'"));
And then to handle your non existant value edge case:
function split(str) {
var i = str.indexOf("'");
if(i > 0)
return str.slice(0, i);
else
return "";
}
Demo on JsFiddle
Nobody seems to have presented what seems to me as the safest and most obvious option that covers each of the cases the OP asked about so I thought I'd offer this:
function getCharsBefore(str, chr) {
var index = str.indexOf(chr);
if (index != -1) {
return(str.substring(0, index));
}
return("");
}
try this
str.substring(0,str.indexOf("'"));
Here is an underscore mixin in coffescript
_.mixin
substrBefore : ->
[char, str] = arguments
return "" unless char?
fn = (s)-> s.substr(0,s.indexOf(char)+1)
return fn(str) if str?
fn
or if you prefer raw javascript : http://jsfiddle.net/snrobot/XsuQd/
You can use this to build a partial like:
var beforeQuote = _.substrBefore("'");
var hasQuote = beforeQuote("14' - €0.88"); // hasQuote = "14'"
var noQoute = beforeQuote("14 €0.88"); // noQuote = ""
Or just call it directly with your string
var beforeQuote = _.substrBefore("'", "14' - €0.88"); // beforeQuote = "14'"
I purposely chose to leave the search character in the results to match its complement mixin substrAfter (here is a demo: http://jsfiddle.net/snrobot/SEAZr/ ). The later mixin was written as a utility to parse url queries. In some cases I am just using location.search which returns a string with the leading ?.
I use "split":
let string = "one-two-three";
let um = string.split('-')[0];
let dois = string.split('-')[1];
let tres = string.split('-')[2];
document.write(tres) //three

How to remove the end of a string, starting from a given pattern?

Let's say I have a string like this:
var str = "/abcd/efgh/ijkl/xxx-1/xxx-2";
How do I, using Javascript and/or jQuery, remove the part of str starting with xxx, till the end of str?
str.substring( 0, str.indexOf( "xxx" ) );
Just:
s.substring(0, s.indexOf("xxx"))
A safer version handling invalid input and lack of matching patterns would be:
function trump(str, pattern) {
var trumped = ""; // default return for invalid string and pattern
if (str && str.length) {
trumped = str;
if (pattern && pattern.length) {
var idx = str.indexOf(pattern);
if (idx != -1) {
trumped = str.substring(0, idx);
}
}
}
return (trumped);
}
which you'd call with:
var s = trump("/abcd/efgh/ijkl/xxx-1/xxx-2", "xxx");
Try using string.slice(start, end):
If you know the exact number of characters you want to remove, from your example:
var str = "/abcd/efgh/ijkl/xxx-1/xxx-2";
new_str = str.slice(0, -11);
This would result in str_new == '/abcd/efgh/ijkl/'
Why this is useful:
If the 'xxx' refers to any string (as the OP said), i.e: 'abc', '1k3', etc, and you do not know beforehand what they could be (i.e: Not constant), the accepted answers, as well as most of the others will not work.
Try this:
str.substring(0, str.indexOf("xxx"));
indexOf will find the position of xxx, and substring will cut out the piece you want.
This will take everything from the start of the string to the beginning of xxx.
str.substring(0,str.indexOf("xxx"));

Any javascript string function?

Some outside code is giving me a string value like..
null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,
now i have to save this value to the data base but putting 0 in place of null in javascript. Is there any javascript string releated function to do this conversion?
You can simply use the replace function over and over again until all instances are replaced, but make sure that all your string will ever contain is the character sequence null or a number (and obviously the delimiting comma):
var str = "null,402,2912,null"
var index = str.indexOf("null");
while(index != -1) {
str = str.replace("null", "0");
index = str.indexOf("null");
}
You need to run a for loop because the function String.replace(search, rplc) will replace only the first instance of search with rplc. So we use the indexOf method to check, in each iteration, if the required term exists or not. Another alternative (and in my opinion, a better alternative would be:
var str = "null,402,2912,null"
var parts = str.split(",");
var data = []
for(var i=0; i<parts.length; i++) {
data[data.length] = parts[i]=="null"?0:parseInt(parts[i]);
}
Basically, what we are doing is that since you will anyways be converting this to an array of numbers (I presume, and sort of hope), we first split it into individual elements and then inspect each element to see if it is null and make the conversion accordingly.
This should answer your needs:
var str = 'null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390';
str.split(",").map(function (n) { var num = Number(n); return isNaN(num) ? 0 : num; });
The simplest solution is:
var inputString = new String("null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,");
var outputString = inputString.replace("null", "0");
What I understood from your question is:
You want to replace null with 0 in a string.
You may use
string = "null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,"
string.replace(/null/g,0)
Hope it helps.

Categories

Resources