How to replace part of string with another in js? - javascript

I'm using js to read an xml file elements and replace some nodes name with another by replacing part of the string, but when running my app nothing happening, that's my code:
$('#dummy').load('cafe.xml',function() {
initialize();
})
function initialize(){
ct=$('menu').children().length;
for(cati==0;cati<=ct-1;cati++)
{
cats[cati]=$('menu').children().eq(cati).prop('nodeName');
// modifing the whitespaces and special characters
var realname = cats[cati];
if(realname.indexOf(".") != -1){
realname.replace(/\./g,' ');
}
if(realname.indexOf("1") != -1){
realname.replace(/\1/g,'\'');
}
if(realname.indexOf("2") != -1){
realname.replace(/\2/g,'&');
}
if(realname.indexOf(":") != -1){
realname.replace(/\:/g,'(');
}
if(realname.indexOf("!") != -1){
realname.replace(/\!/g,')');
}
if(realname.indexOf("0") != -1){
realname.replace(/\0/g,'/');
}
}

replace doesn't change the original string. Try with something like
realname = realname.replace(/.../g, "...");
Anyway, I'd ditch all those if, that are kind of useless given what you're doing.

Related

How to: $(this) ToUpperCase

I'm no professional and after research, I wasn't able to find a solution.
I have a JavaScript source code for a SharePoint list to implement the InstantListFilter (https://archive.codeplex.com/?p=instantlistfilter) which works!
But I would like to update the source code so that the filter is NOT case sensitive. I was able to replace the the filter word (val) to uppercase (val = val.toUpperCase()). But I have no idea how to get the list-text to uppercase.
$("table.ms-listviewtable").children("tbody").each(function() {
$(this).children("tr").each(function() {
var mismatch = false;
$(this).children("td").each(function(colIndex) {
if (mismatch) return;
if (filterValues[colIndex]) {
var val = filterValues[colIndex];
// replace double quote character with 2 instances of itself
val = val.replace(/"/g, String.fromCharCode(34) + String.fromCharCode(34));
val = val.toUpperCase(); //my adaption, working for the filter word
$(this).val = $(this).val().toUpperCase(); //not working for the list-text
// verifies the filter word.
if ($(this).is(":not(:contains('" + val + "'))")) {
mismatch = true;
}
}
});
if (mismatch) {
$(this).hide();
} else {
$(this).show();
}
});
});
Does anybody have a solution?
Would be happy with a short reply!
The solution you are trying will also modify the input value to upper case, i'm not sure you want that? Maybe you could assign the input value to a var and see if it contains the text with String.indexOf()
...
val = val.toUpperCase(); //my adaption, working for the filter word
var inputVal = $(this).val().toUpperCase();
// indexOf = -1 means that inputVal does not contain val
if (inputVal.indexOf(val) === -1) {
mismatch = true;
}
...
thanks for reply!!!
I got it:
var inputVal = $(this).text().toUpperCase();
//alert(inputVal);
// verifies the filter word.
// indexOf = -1 means that inputVal does not contain val
if (inputVal.indexOf(val.toUpperCase()) === -1) {
mismatch = true;
}

How to check if string contains '?' using javascript

I'm trying to check if an url contains a query string or not.
Lets say we have these two url's.
http://localhost:3000/userbookings/list
http://localhost:3000/userbookings/list?resource=de
My string is called fullPath, and I need to check if it contains the ?, so I know if its a query string or not.
Have tried with the following code:
if (fullPath.indexOf("?") > -1){
content = fs-readFileSync('http://localhost:3000/userbookings/list1');
}
else {
content = fs.readFileSync(fullPath);
}
Your way should work too but if you want in the future to use more complex qualifiers you could start using regular expressions:
var pattern = /\?/g;
var found = fullPath.match(pattern) != null;
alert(found);
this help you :
<html>
<head>
</head>
<body>
<script>
var str = "this is ?text";
var patt = /\?/gi;
if(str.search(patt)!=-1)
alert("Found");
else
alert("No found");
</script>
</body>
</html>
Like this:
if (str.indexOf("?") >= 0)
Or,
if (/\?/i.test(str))
Or,
if(str.includes('?'))
Please note that String.includes is an EcmaScript 6 feature and may not work in some browsers.
I think your goal is just to check if there's a php get variable right??
if(document.localtion.search != "") {
// Your code
}
The document.location.search will be "?resource=de" if you visit the url
http://localhost:3000/userbookings/list?resource=de
And it will be "" if you visit the url
http://localhost:3000/userbookings/list
Answer #2
check = document.location.split("?");
if(check.length > 1) {
//do your code
}
splitting the http://localhost:3000/userbookings/list?resource=de url using "?" will be splitted by 2.
And splitting the http://localhost:3000/userbookings/list url using "?" wil result by 1.
Answer #3
check = fullpath.replace("?","");
if(check != fullpath) {
//do your code
}
Removing the "?" in the full path. If the check is the same as fullpath then it doesn't have a "?"
I think this might help you out. Feel free to comment

jquery href .indexOf, how to exclude

Let's say I'm on www.forum.com, and, other than the homepage, the URL always has all kinds of additional text, for example, www.forum.com/post1/oh-yeah or www.forum.com/post999/oh-baby but I want to create an if statement that excludes everything other than www.forum.com, how do I do this?
In other words, how to do this:
if ( href.indexOf('forum.com') === 'forum.com' ){
console.log('href value is exactly forum.com, with no additional string');
} else {
console.log('href url contains more than just forum.com');
}
Gracias.
When you invoke the href.indexOf('forum.com') The result is an integer. In a case you get -1, it is because it is non existent.
The indexOf() method returns the position of the first occurrence of a
specified value in a string.
This method returns -1 if the value to search for never occurs.
For more information
So instead of (href.indexOf('forum.com') === 'forum.com') you need to do (href.indexOf('/') == -1) which would mean that there is nothing after www.forum.com
if (href.indexOf('/') == -1) {
console.log('href value is exactly forum.com, with no additional string');
} else {
console.log('href url contains more than just forum.com');
}
This code snippet may help
href = "www.forum.com/test-1";
if (href.indexOf('/') == -1) {
document.getElementById("test").innerHTML = "href value is exactly forum.com, with no additional string";
} else {
document.getElementById("test").innerHTML = "href url contains more than just forum.com";
}
href = "www.forum.com";
if (href.indexOf('/') == -1) {
document.getElementById("test1").innerHTML = "href value is exactly forum.com, with no additional string";
} else {
document.getElementById("test1").innerHTML = "href url contains more than just forum.com";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="test">Test</p>
<p id="test1">Test</p>
The answers you have here so far are all good. I just going to include something else you might want to consider. If you are trying to grab the url and then look for anything after the hostname, you might want to simply check like this:
if(window.location.pathname != '' || window.location.search != ''){
//stuff after the current url
}
window.location.pathname will handle both examples you provided. If your url has query strings (things with ? in them), then window.location.search will handle that.
This will be another good solution.
var href="www.forum.com";
//ADDED href.indexOf("www.forum.com")==0 for extra verification
if (href.match("www.forum.com$") && href.indexOf("www.forum.com")==0) {
alert("ONLY URL");
}
else
{
alert("URL CONTAINS SOMETHING EXTRA");
}
WORKING FIDDLE

Javascript split result simplify

Is there a way to make this code more simplified?
<input type="text" id="tags" />
var splittext = document.getElementById('tags').value.split(' ');
if (document.getElementById('tags').value.split(' ').length < 2 || splittext[1] == '') {
alert("Two tags required.");
}
is there another way to make
splittext[1] == ''
be like
document.getElementById('tags').value.split(' ').something[1]
to avoid using the line
var splittext = document.getElementById('tags').value.split(' ')
The purpose of this is when a user inputs one tag and made a space after it, the split detects 2 values which i would like to avoid the space being counted as another tag because that would be like, uhm, cheating.
Trim first, and split on any number of white space characters:
if (document.getElementById('tags').value.trim( ).split(/\s+/).length < 2) {
alert("Two tags required.");
}
You will need to create the String.trim function if you want to support some versions of IE though... but it's a useful function to have. Put this in a utility js file, or just at the top of your js:
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
You should change your code to this to avoid making multiple calls to the same dom element(you are splitting the same thing twice)
var splittext = document.getElementById('tags').value.split(' ');
if (splittext.length < 2 || splittext[1] == '') {
alert("Two tags required.");
}
This is the whole point of using variables, to avoid calling the same function(with the same results) multiple times.
Something like this should do the trick:
var elem=document.getElementById('tags').value;
if(elem.indexOf(' ')>-1 && elem.split(' ').length>=2) {
alert('Worked!');
} else if(!elem || elem.indexOf(' ')<0) {
alert('Two tags required.');
}
yeah :
var g= document.getElementById('tags').value.split(/[ ]+/)
if (g.length==2) // ok.....
http://jsbin.com/ovibef/edit#javascript,html

Javascript Regular Expression [Remove Events]

does anyone know of a good regular expression to remove events from html.
For example the string:
"<h1 onmouseover="top.location='http://www.google.com">Large Text</h1>
Becomes
"<h1>Large Text</h1>
So HTML tags are preserved but events like onmouseover, onmouseout, onclick, etc. are removed.
Thanks in Advance!
How about:
data.replace(/ on\w+="[^"]*"/g, '');
Edit from the comments:
This is intended to be run on your markup as a one time thing. If you're trying to remove events dynamically during the execution of the page, that's a slightly different story. A javascript library like jQuery makes it extremely easy, though:
$('*').unbind();
Edit:
Restricting this to only within tags is a lot harder. I'm not confident it can be done with a single regex expression. However, this should get you by if no one can come up with one:
var matched;
do
{
matched = false;
data = data.replace(/(<[^>]+)( on\w+="[^"]*")+/g,
function(match, goodPart)
{
matched = true;
return goodPart;
});
} while(matched);
Edit:
I surrender at writing a single regex for this. There must be some way to check the context of a match without actually capturing the beginning of the tag in your match, but my RegEx-fu is not strong enough. This is the most elegant solution I'm going to come up with:
data = data.replace(/<[^>]+/g, function(match)
{
return match.replace(/ on\w+="[^"]*"/g, '');
});
Here's a pure JS way to do it:
function clean(html) {
function stripHTML(){
html = html.slice(0, strip) + html.slice(j);
j = strip;
strip = false;
}
function isValidTagChar(str) {
return str.match(/[a-z?\\\/!]/i);
}
var strip = false; //keeps track of index to strip from
var lastQuote = false; //keeps track of whether or not we're inside quotes and what type of quotes
for(var i=0; i<html.length; i++){
if(html[i] === "<" && html[i+1] && isValidTagChar(html[i+1])) {
i++;
//Enter element
for(var j=i; j<html.length; j++){
if(!lastQuote && html[j] === ">"){
if(strip) {
stripHTML();
}
i = j;
break;
}
if(lastQuote === html[j]){
lastQuote = false;
continue;
}
if(!lastQuote && html[j-1] === "=" && (html[j] === "'" || html[j] === '"')){
lastQuote = html[j];
}
//Find on statements
if(!lastQuote && html[j-2] === " " && html[j-1] === "o" && html[j] === "n"){
strip = j-2;
}
if(strip && html[j] === " " && !lastQuote){
stripHTML();
}
}
}
}
return html;
}

Categories