loop through and .replace using regex - javascript

I have a list of url extensions that i want to string replace using regex so that both upper and lower case is captured like this:
str = str.replace(/\.net/i,"")
.replace(/\.com/i,"")
.replace(/\.org/i,"")
.replace(/\.net/i,"")
.replace(/\.int/i,"")
.replace(/\.edu/i,"")
.replace(/\.gov/i,"")
.replace(/\.mil/i,"")
.replace(/\.arpa/i,"")
.replace(/\.ac/i,"")
.replace(/\.ad/i,"")
.replace(/\.ae/i,"")
.replace(/\.af/i,"");
When i try to clean this up using arrays and loops like so, i get an error. Can anyone help me with syntax please
var arr = [ "net","com","org","net","int","edu","gov","mil","arpa","ac","ad","ae"];
str = str.replace(/\.com/i,"")
for(ii==0;ii<=arr.length;ii++){
.replace('/\.'+arr[ii]+'/i',"") // i know this '/\.' and '/i' should not be a string but how would i write it?
}
.replace(/\.af/i,"");

You can just do like this instead of running replace multiple times in a loop:
str = str.replace(/\.(com|net|org|gov|edu|ad|ae|ac|int)/gi, '');

You need to create a RegExp object. You also need to apply .replace to the string, and assign the result.
for (ii = 0; ii < arr.length; ii++) {
str = str.replace(new Regexp('\\.' + arr[ii], 'i'));
}

Related

How to find a particular char in string in my case "-" and replace it with "_" in javascript js

Hey guys i am currently learning javascript, i need to replace "-" with "_".
For example : "Hello-World" ==> "Hello_World" i tired the below code it didn't work,i want to know why this method is wrong,
function kS(n){
j=n.length;
for(i=0;i<j;i++){
if(n[i]=="-")
{
n[i]="_";
console.log(n);
}
}
}
Simply use replace
console.log("Hello-World".replace('-','_'))
You can just use String.replace to achieve that. If you use the regex input in combination with g modifier, it will match all occurences. https://regex101.com/ is a good place to test out such regexes.
var myString = "hello-word";
myString = myString.replace(/-/g, '_');
If you have to do it with a loop and are allowed to use ES2015 or newer, you could also write it like this:
var myString = "hello-word";
var newString = [...myString].map(c => c === '-' ? '_' : c).join('');
Stings are immutable. You could convert the string to an array of characters and check and replace the item in the characters array.
At the end return a joined array.
BTW, spelling matter, eg length and undeclared variables are global in Javascript, which should be avoided.
function kS([...characters]) {
var l = characters.length;
for (var i = 0; i < l; i++) {
if (characters[i] === "-") characters[i] = "_";
}
return characters.join('');
}
console.log(kS('1-2-3'));

Javascript regex to add to every character of a string a backslash

So as the title says I'd like to add to every character of a string a backslash, whether the string has special characters or not. The string should not be considered 'safe'
eg:
let str = 'dj%^3&something';
str = str.replace(x, y);
// str = '\d\j\%\^\3\&\s\o\m\e\t\h\i\n\g'
You could capture every character in the string with (.) and use \\$1 as replacement, I'm not an expert but basically \\ will render to \ and $1 will render to whatever (.) captures.
HIH
EDIT
please refer to Wiktor Stribiżew's comment for an alternative which will require less coding. Changes as follows:
str = str.replace(/(.)/g, '\\$1'); for str = str.replace(/./g, '\\$&');
Also, for future reference I strongly advice you to visit regexr.com when it comes to regular expressions, it's helped ME a lot
let str = 'dj%^3&something';
str = str.replace(/(.)/g, '\\$1');
console.log(str);
If you just want to display a string safely, you should just do:
let str = 'dj%^3&something';
let node = document.createTextNode(str);
let dest = document.querySelector('.whatever');
dest.appendChild(node);
And then you are guaranteed that it will be treated as text, and won't be able to execute a script or anything.
For example: https://jsfiddle.net/s6udj03L/1/
You can split the string to an array, add a \ to each element to the array, then joint the array back to the string that you wanted.
var str = 'dj%^3&something';
var split = str.split(""); // split string into array
for (var i = 0; i < split.length; i++) {
split[i] = '\\' + split[i]; // add backslash to each element in array
}
var joint = split.join('') // joint array to string
console.log(joint);
If you don't care about creating a new string and don't really have to use a regex, why not just iterate over the existing one and place a \ before each char. Notice to you have to put \\ to escape the first \.
To consider it safe, you have to encode it somehow. You could replace typical 'non-safe' characters like in the encode() function below. Notice how & get's replaced by &
let str = 'dj%^3&something';
let out = "";
for(var i = 0; i < str.length; i++) {
out += ("\\" + str[i]);
}
console.log(out);
console.log(encode(out));
function encode(string) {
return String(string).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}

Is there a simple one-liner to split and join a string?

I have a string which looks likes this:
obj.property1.property2
I want the string to become
[obj][property1][property2]
Currently I use a split and later on a for loop to join each other. But I was wondering if there was a more simpler method for doing this, perhaps with using split() and join() toghether. I can't figure out how however.
Currently using:
var string = "obj.property1.property2";
var array = string.split(".");
var output = "";
for(var i = 0;i < array.length;i++) {
output += "[" + array[i] + "]";
};
console.log(output);
Consider using replace with the RegEx global option to replace all instances of '.' with back to back braces, then stick an opening and closing brace on the end like this.
var str ="obj.property1.property2"
console.log("["+str.replace(/\./g,"][")+"]")
'['+string.split('.').join('][')+']'

Extracting substring based on the occurrence of a character using javascript

I have the following string.
http://localhost:8080/test/tf/junk?tx=abc&xy=12345
Now I want to get substring between the third and fourth slash "/" using javascript.
To be more clear, I want to extract test from the above given string.
Can anybody help me out on this?
You can split your string into an array
var str = "http://localhost:8080/test/tf/junk?tx=abc&xy=12345";
str = str.replace("http://", "");
var array = str.split("/");
for(var i = 0; i < array.length; i++) {
alert(array[i]);
}

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