Javascript Replace with Global not working on Caret Symbol - javascript

i have following code for replacing
var temp = "^hall^,^restaurant^";
temp.replace(/^/g, '');
console.log(temp);
This does not Replace the ^ symbol from string. How can this not work?

temp = temp.replace(/\^/g, '');
It is replacing once you escape the caret.
https://jsfiddle.net/ym7tt1L8/
And note that just writing temp.replace(/\^/g, ''); doesn't update your actual string. That is the reason you have to write
temp = temp.replace(/\^/g, '');

In RegEx, the caret symbol is a recognized as a special character. It means the beginning of a string.
Additionally, replace returns the new value, it does not perform the operation in place, youneed to create a new variable.
For your case, you have to do one of the following:
var temp = "^hall^,^restaurant^";
var newString = temp.replace(/\^/g, ''); // Escape the caret
Or simply replace the character without using RegEx at all:
var temp = "^hall^,^restaurant^";
while (temp.indexOf('^') >= 0) {
temp = temp.replace('^', '');
}
Alternative version:
var temp = "^hall^,^restaurant^";
var newString = temp.split('^').join('');

Related

How to String include after character in nodejs, JavaScript

I want to do this in node.js
example.js
var str = "a#universe.dev";
var n = str.includes("b#universe.dev");
console.log(n);
but with restriction, so it can search for that string only after the character in this example # so if the new search string would be c#universe.dev it would still find it as the same string and outputs true because it's same "domain" and what's before the character in this example everything before # would be ignored.
Hope someone can help, please
Look into String.prototype.endsWith: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
First, you need to get the end of the first string.
var ending = "#" + str.split("#").reverse()[0];
I split your string by the # character, so that something like "abc#def#ghi" becomes the array ["abc", "def", "ghi"]. I get the last match by reversing the array and grabbing the first element, but there are multiple ways of doing this. I add the separator character back to the beginning.
Then, check whether your new string ends the same:
var n = str.endsWith(ending);
console.log(n);
var str = "a#universe.dev";
var str2 = 'c#universe.dev';
str = str.split('#');
str2 = str2.split('#');
console.log(str[1] ===str2[1]);
With split you can split string based on the # character. and then check for the element on position 1, which will always be the string after #.
Declare the function
function stringIncludeAfterCharacter(s1, s2, c) {
return s1.substr(s1.indexOf(c)) === s2.substr(s2.indexOf(c));
}
then use it
console.log(stringIncludeAfterCharacter('a#universe.dev', 'b#universe.dev', '#' ));
var str = "a#universe.dev";
var n = str.includes(str.split('#')[1]);
console.log(n);
Another way !
var str = "a#universe.dev";
var n = str.indexOf(("b#universe.dev").split('#')[1]) > -1;
console.log(n);

Regex remove all string start with special character

I have a string look like:
var str = https://sharengay.com/movie13.m3u8?pid=144.21.112.0&tcp=none
I want to remove at start ?pid= to end. The result look like:
var str = https://sharengay.com/movie13.m3u8
I tried to:
str = str.replace(/^(?:?pid=)+/g, "");
But it show error like:
Invalid regular expression: /^(?:?pid=)+/: Nothing to repeat
If you really want to do this at the string level with regex, it's simply replacing /\?pid=.*$/ with "":
str = str.replace(/\?pid=.*$/, "");
That matches ?pid= and everything that follows it (.*) through the end of the string ($).
Live Example:
var str = "https://sharengay.com/movie13.m3u8?pid=144.21.112.0&tcp=none";
str = str.replace(/\?pid=.*$/, "");
console.log(str);
You can use split
var str = "https://sharengay.com/movie13.m3u8?pid=144.21.112.0&tcp=none"
var result = str.split("?pid=")[0];
console.log(result);
You can simply use split(), which i think is simple and easy.
var str = "https://sharengay.com/movie13.m3u8?pid=144.21.112.0&tcp=none";
str = str.split("?pid");
console.log(str[0]);
You may create a URL object and concatenate the origin and the pathname:
var str = "https://sharengay.com/movie13.m3u8?pid=144.21.112.0&tcp=none";
var url = new URL(str);
console.log(url.origin + url.pathname);
You have to escape the ? and if you want to remove everything from that point you also need a .+:
str = str.replace(/\?pid=.+$/, "")
You can use split function to get only url without query string.
Here is the example.
var str = 'https://sharengay.com/movie13.m3u8?pid=144.21.112.0&tcp=none';
var data = str.split("?");
alert(data[0]);

Manipulate input string while doing a regex search

trying to find every match in a string and process it with a custom function and replace it in the string. When I set text = to the new string though, it never changes, and in the end remains the unchanged.
function submit () {
var searchTerm = document.querySelector('#search-term').value;
var replaceFunction = Function('input', document.querySelector('#function').value);
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
var output = text;
var regex = new RegExp('\d', 'g');
var match, matches = [];
//search for replacements
while ((match = regex.exec(text)) != null) {
var beforeMatch = output.substring(0, match.index);
var afterMatch = output.substring(match.index + match[0].length, text.length);
text = beforeMatch + replaceFunction(match[0]) + afterMatch;
console.log(text);
}
console.log('result', text);
}
function replaceFunction (input) {
return input * 2;
}
You can achieve same result with far less code using replace() and its function's callback that takes match as parameter.
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
text = text.replace(/\d+/g, function(match){
return parseInt(match) * 2;
})
console.log(text)
First of all, you need to use \\ for escape sequence if you are using RegExp constructor. Alternatively you can use the RegExp literal as shown below. Moreover you are using only \d which is going to match a single digit. Instead you should be using \d+ that will match the complete number.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
When using the constructor function, the normal string escape rules
(preceding special characters with \ when included in a string) are
necessary. For example, the following are equivalent:
var re = /\w+/;
var re = new RegExp('\\w+');
Then you are trying to manipulate the string using a loop. Instead simply use replace function as shown below.
function submit () {
// var searchTerm = document.querySelector('#search-term').value;
// var replaceFunction = Function('input', document.querySelector('#function').value);
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
var output = text;
var regex = new RegExp('\\d+', 'g'); // <<<<<< RegExp constructor
// OR
regex = /\d+/g; // <<<<<<< RegExp literal
var match, matches = [];
console.log(text);
output = text.replace(regex, replaceFunction);
console.log('result', output);
}
function replaceFunction (input) {
return parseInt(input) * 2;
}
submit();
Disclaimer: Using RegExp for manipulating HTML elements and attributes is not a good idea and you may end up in unexpected issues if its not used carefully. Use it at your own risk.

Removing commas unless inside quotes, not using regexp

I am trying to remove commas in a string unless they appear inside quotes.
var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '';
mystring = mystring.split(',').join(newchar);// working correctly
document.write(mystring);
Output I have is
this is a test example "i dont know" jumps
Expected output
this is a test example "i, dont know" jumps
A couple of questions. How can I find the index of string so that inside the quotation it will include comma but outside of quotation " it will not include comma ,. I know I have to use indexOf and substring but I don't know how to format it? (No regex please as I'm new to JavaScript and I'm just focusing on the basics.)
Loop through the string, remembering whether or not you are inside a set of quotation marks, and building a new string to which the commas inside quotes are not added:
var inQuotes = false; // Are we inside quotes?
var result = ''; // New string we will build.
for (var i = 0; i < str.length; i++) { // Loop through string.
var chr = str[i]; // Extract character.
var isComma = chr === ','; // Is this a comma?
var isQuote = chr === '"'; // Is this a quote?
if (inQuotes || !isComma) { // Include this character?
if (isQuote) inQuotes = !inQuotes; // If quote, reverse quote status.
result += chr; // Add character to result.
}
}
This solution has the advantage compared to the accepted one that it will work properly even if the input has multiple quotes strings inside it.
This will work, but it's not ideal for all cases. Example: It will not work for a string with more than 2 quotation marks.
var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '';
var firstIndex = mystring.indexOf("\"");
var lastIndex = mystring.lastIndexOf("\"");
var substring1 = mystring.substring(0,firstIndex).split(',').join(newchar);
var substring2 = mystring.substring(lastIndex).split(',').join(newchar);
mystring = substring1 + mystring.substring(firstIndex, lastIndex) + substring2;
document.write(mystring);
Some day you need to start using regexp, than regexr.com is your friend. The regexp solution is simple:
var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '_';
mystring = mystring.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g).join(newchar);// working correctly
document.write(mystring);

Regular Expression in JS

How do you trim all of the text after a comma using JS?
I have: string = Doyletown, PA
I want: string = Doyletown
var str = 'Doyletown, PA';
var newstr=str.substring(0,str.indexOf(',')) || str;
I added the || str to handle a scenario where the string has no comma
How about a split:
var string = 'Doyletown, PA';
var parts = string.split(',');
if (parts.length > 0) {
var result = parts[0];
alert(result); // alerts Doyletown
}
using regular expression it will be like:
var str = "Doyletown, PA"
var matches = str.match(/^([^,]+)/);
alert(matches[1]);
jsFiddle
btw: I would also prefer .split() method
Or more generally (getting all the words in a comma separated list):
//Gets all the words/sentences in a comma separated list and trims these words/sentences to get rid of outer spaces and other whitespace.
var matches = str.match(/[^,\s]+[^,]*[^,\s]+/g);
Try this:
str = str.replace(/,.*/, '');
Or play with this jsfiddle

Categories