Using regex to split double hyphen but not single hyphen - javascript

I have an html element id that looks like this:
dp__1-2--1-3
I'm trying to use the JavaScript split() function to lop off and return the final '1-3'
My regex skills are poor but a bit of searching around got me to this point:
var myId = "dp__1-2--1-3";
var myIdPostFix = myId.split(/[\-\-]+/).pop();
Unfortunately that returns me only the '3'.
So my question is how do I split double hyphens but NOT single hyphens?

It's the brackets in the regular expression that keeps it from working. A set will match one of any of the characers in it, so [\-\-] is the same as [\-], i.e. matching a single hyphen.
Just remove the brackets:
var myIdPostFix = myId.split(/--/).pop();
or just use the string '--' instead of a regular expression:
var myIdPostFix = myId.split('--').pop();

split accepts a regular expression or a string as the first argument.
You were very close. You can achieve what you want with:
var myIdPostFix = myId.split("--").pop();

Related

Insert Character on String Javascript

Hi I want to insert additional character on strings from "replace" function.
example
string = "AGAS Ranges"
find = "gas"
my code
string.toLowerCase().replace("gas", `<b>${find}</b>`)
i want the result is like this, only add b and /b tag from the character you are looking for without changing the original words
"A<b>GAS</b> Ranges"
Thanks
The pattern can be a RegExp, so you can reference to first matched group like $1.
i modifier - makes the regex case insensitive.
console.log("AGAS Ranges".replace(/(gas)/i, "<b>$1</b>"))
Use a variable in a regular expression:
const string = 'AGAS Ranges';
const find = 'gas';
const regExp = new RegExp(`(${find})`, 'i');
console.log(string.replace(regExp, '<b>$1</b>'));

How to get next 3 characters after a substring if it exist inside a string?

I have this string that's. The &# substring is common but number after it changes in almost every object of my JSON data. So I want to detect if there is this substring, then get next three characters after it replace it with something else. How can I do it?
You can do it like this
var para = 'that's';
para = para.substr(para.indexOf('#')+1, 3);
syntax:
substr(start, length)
indexOf(searchvalue, [start])
Assuming you want to replace everything from &# until ; (if not, please update your question by specifying expected output):
You can use String.prototype.replace() with a regular expression:
var para = 'some string ' middle † end';
para = para.replace(/&#([\d]*);/g, 'replacement');
The g modifier is important to replace all occurences in the string.
With the RegEx used, you can include the found number (between &# and ;) in the replacement string by using $1.
you can define and use a utility function to replace HTML entities like that:
function decode(text, replaceWith = '') {
return text.replace(/&#(\d+);/g, replaceWith)
}

How would I write a Regular Expression to capture the value between Last Slash and Query String?

Problem:
Extract image file name from CDN address similar to the following:
https://cdnstorage.api.com/v0/b/my-app.com/o/photo%2FB%_2.jpeg?alt=media&token=4e32-a1a2-c48e6c91a2ba
Two-stage Solution:
I am using two regular expressions to retrieve the file name:
var postLastSlashRegEx = /[^\/]+$/,
preQueryRegEx = /^([^?]+)/;
var fileFromURL = urlString.match(postLastSlashRegEx)[0].match(preQueryRegEx)[0];
// fileFromURL = "photo%2FB%_2.jpeg"
Question:
Is there a way I can combine both regular expressions?
I've tried using capture groups, but haven't been able to produce a working solution.
From my comment
You can use a lookahead to find the "?" and use [^/] to match any non-slash characters.
/[^/]+(?=\?)/
To remove the dependency on the URL needing a "?", you can make the lookahead match a question mark or the end of line indicator (represented by $), but make sure the first glob is non-greedy.
/[^/]+?(?=\?|$)/
You don't have to use regex, you can just use split and substr.
var str = "https://cdnstorage.api.com/v0/b/my-app.com/o/photo%2FB%_2.jpeg?alt=media&token=4e32-a1a2-c48e6c91a2ba".split("?")[0];
var fileName = temp.substr(temp.lastIndexOf('/')+1);
but if regex is important to you, then:
str.match(/[^?]*\/([^?]+)/)[1]
The code using the substring method would look like the following -
var fileFromURL = urlString.substring(urlString.lastIndexOf('/') + 1, urlString.lastIndexOf('?'))

Finding the xml escaped dash in Javascript

I want to use regular expression to find dashes in an html in javascript. The dashes in html pages sometimes may be xml escaped with the string value of –. However, using regular expression to find this string is not working for some reason.
var html = document.getElementsByTagName('html').item(0).innerHTML;
var escapedDash = /–/ig;
var foundEscapedDash = html.match(escapedDash);
alert(foundEscapedDash);
The regular experession, /–/ig does not result in any values. Nor does the regular expression /-/i find the escaped dash –
Does anyone know of a regular expression that can find the escaped dash?
When you set innerHTML to a string with an entity, it converts it to the literal character. For example:
var div = document.createElement('div');
div.innerHTML = '–'
alert(div.innerHTML.length); // 1, not 7 as may be expected
So you need to match the actual character &ndash, and to do that, you can use the unicode literal representation. For "–", it's \u2013.
div.innerHTML.match(/\u2013/ig)
By the way, assuming the dash is the first character of the string, you can find the hex number 0x2013 for yourself with div.innerHTML.charCodeAt(0).toString(16).
Try this:
var str = '–hello world –';
var escapedDash = /(–+)/ig;
var foundEscapedDash = str.match(escapedDash);
alert(foundEscapedDash);

How to replace multiple strings with replace() in Javascript

I'm guessing this is a simple problem, but I'm just learning...
I have this:
var location = (jQuery.url.attr("host"))+(jQuery.url.attr("path"));
locationClean = location.replace('/',' ');
locationArray = locationClean.split(" ");
console.log(location);
console.log(locationClean);
console.log(locationArray);
And here is what I am getting in Firebug:
stormink.net/discussed/the-ideas-behind-my-redesign
stormink.net discussed/the-ideas-behind-my-redesign
["stormink.net", "discussed/the-ideas-behind-my-redesign"]
So for some reason, the replace is only happening once? Do I need to use Regex instead with "/g" to make it repeat? And if so, how would I specifiy a '/' in Regex? (I understand very little of how to use Regex).
Thanks all.
Use a pattern instead of a string, which you can use with the "global" modifier
locationClean = location.replace(/\//g,' ');
The replace method only replaces the first occurance when you use a string as the first parameter. You have to use a regular expression to replace all occurances:
locationClean = location.replace(/\//g,' ');
(As the slash characters are used to delimit the regular expression literal, you need to escape the slash inside the excpression with a backslash.)
Still, why are you not just splitting on the '/' character instead?
You could directly split using the / character as the separator:
var loc = location.host + location.pathname, // loc variable used for tesing
locationArray = loc.split("/");
This can be fixed from your javascript.
SYNTAX
stringObject.replace(findstring,newstring)
findstring: Required. Specifies a string value to find. To perform a global search add a 'g' flag to this parameter and to perform a case-insensitive search add an 'i' flag.
newstring: Required. Specifies the string to replace the found value from findstring
Here's what ur code shud look like:
locationClean = location.replace(new RegExp('/','g'),' ');
locationArray = locationClean.split(" ");
njoi'

Categories

Resources