Replace a word in a string using JQuery - javascript

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.

Related

How to add a variable to a regex checking for a URL?

I have this part of a function which is running perfectly:
if(/https?:\/\/[a-z]{2}w?\.mywebsite\./.test(href)){
if(!firstSerp){
firstSerp = this;
add_prerender(this, href);
}
}
As you can see mywebsite is hard-coded. What I want is to put a variable there instead.
So it would look like this:
var mylink = 'mywebsite';
if(/https?:\/\/[a-z]{2}w?\.+= mylink\./.test(href)){}
One of the users suggested I look at How do you use a variable in a regular expression?
var replace = "regex";
var re = new RegExp(replace,"g");
But I have difficulties understanding how that would apply to my example.
Could you please help me solve this?
Regular expressions are intended to be used to check if an existing string matches a pattern or to find a pattern in an existing string. You cannot use them to build a string.
Instead, you should use string concatenation:
const url = 'http://www.' + mywebsite + '.com';
or a string template:
const url = `http://www.${mywebsite}.com`;

How to get a text from a string with symbol using javascript

I am trying to get variable with \ symbol from a string.but not working.
var prevLink='../my-test-pack/mvc';
var actLink=prevLink.remove('..').remove('/').join('\');
console.log(actLink);
//output actLink should be like actLink='\my-test-pack\mvc';
prevLink dynamically will change like
var prevLink='../my-test-pack/mvc/svc'; or var prevLink='../my-test-pack/mvc/skg';
but my output should be like
actLink='\my-test-pack\mvc\svc'; or actLink='\my-test-pack\mvc\skg';
How to get that?Anyone can help to get this value?
You should try (this will also change / to \ as you wished
var prevLink='../my-test-pack/mvc';
var actLink=prevLink.replace(/\//g, "\\").split("..")[1];
console.log(actLink)
Firstly, strings have no remove() method. Use replace() instead. Secondly, you need to split() the string before you join() it again. Also note that you need to escape the \ as it has a special meaning in JS:
var prevLink = '../my-test-pack/mvc';
var actLink = prevLink.replace('..', '').split('/').join('\\');
console.log(actLink);

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.

Using an array of regex expressions for .match

I have something I am trying to accomplish.
I'd like to take an array built with AJAX/xml.
array[/word0/, /word1/, /word2/]
and put this into a form that could be used in a .match():
result = string.match(array)
I have tried using a for loop and stepping through the array using string.match(array[i]) to no avail.
Is there an easy way to do this?
Edit: You may have a syntax problem. The following is not valid syntax:
array[/word0/, /word1/, /word2/]
Something like this fixes it:
var regexps = [/word0/, /word1/, /word2/];
Original answer:
Javascript RegExps already do this. You're looking for:
var regexp = /word0|word1|word2/;
Assuming your list of matches comes back in the right format, you could achieve this like so:
var words = ["word0", "word1", "word2"];
var regexp = new Regexp(words.join("|"));
str.match(regexp);
http://jsfiddle.net/KALPh/
Your approach was fine. Here's my implementation:
var regexes = [/^def/, /^abc/],
testString = 'abcdef',
numRegexes = regexes.length;
for(var x=0;x<numRegexes;x++) {
alert(regexes[x].test(testString));
}
To initialize your array, use
var array = [/word0/, /word1/, /word2/];
Then you can use
str.match(array[i])
If your problem is the transmission in "AJAX/xml", then you'll need to build the regular expressions client side with new RegExp(somestring) where somestring might for example be "word0" : you can't embed a regex literal in XML.

How to substring in jquery

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>

Categories