Concatenating with Regular Expressions - javascript

I have a JQuery function that grabs the URL path and adds it as a body class as such:
var pathname = window.location.pathname;
var pathSlashesReplaced = pathname.replace(/\//g, " ");
var pathSlashesReplacedNoFirstDash = pathSlashesReplaced.replace(" ","");
var newClass = pathSlashesReplacedNoFirstDash.replace(/\(\d*\)/g, '').replace(/\s/, '-');
$("body").addClass(newClass);
if ( $("body").attr("class") == "")
{
$("body").addClass("class");
}
.. so if the url is something like /myapp/user/list, the body class ends up as:
<body class="myapp-user list">
The issue is I would like to have all three words with dashes so it should be:
<body class="myapp-user-list">
.. and then I can theme using the CSS:
.myapp-user-list {
}
I am pretty sure there is an issue with my RegEx but I cannot figure out where. I tried various text functions but then the problem was that it grabbed all the text from the page and put that in as the body class:
var text = $(this).text();
var newClass = $.trim(text.replace(/\(\d*\)/g, '').toLowerCase()).replace(/\s/, '-');

Try :
var newClass = location.pathname.split('/').join('-').replace(/(^-|-$)/g,''),
$body = $("body").addClass(newClass);
if ($body.attr("class") == "") {
$body.addClass("class");
}
I would avoid the class name class. It could give problems.

Try adding g modifier to the second replace to replace all white spaces and not just the first.
var newClass = pathSlashesReplacedNoFirstDash.replace(/\(\d*\)/g, '').replace(/\s/g, '-');

I think that applying these two regexps will do the job.
"/\//-/g" Will change all slashes to -
"/-//" Will only remove the first -

Related

replace 2 different sets of words in a string in javascript

so I need to replace 2 sets of words in a string; the title of the web page. However, I seem to be able to get one set of words to be removed.
The title is being created by wordpress, which is adding words at the start and end of the title which I don't want to be displayed (as I am calling the title, using PHP, to dynamically create a few bits of information on the page, which are subject to change)
The code I have so far is:
<script>
var str = document.title.replace(/ - CompanyName/i, '');
document.write(str);
</script>
However, I need something which is basically:
var str = document.title.replace(/ - CompanyName/i, '') && document.title.replace(/The /i, '');
This is because the title will produce itself like "The PAGETITLE - CompanyName"
Any ideas how to remove 2 sections of the same string?
Keep the title in a separate variable, re-assign the variable with the result of each replace, set the document title:
var title = "The PAGETITLE - CompanyName";
title = title.replace("The ", "");
title = title.replace(" - CompanyName", "");
document.title = title;
Or, if you like one-liners:
document.title = document.title.replace("The ", "").replace(" - CompanyName", "");
you can directly use like this
var title = "The PAGETITLE - CompanyName";
title.replace(/The(.*?)-[^-]*/,'$1')
var str = document.title.replace(/ - CompanyName/i, '').replace(/The
/i, '');
the replace function yields the new string, which you want to run through replace again.
You can chain functions in JQuery like this:
var str = document.title.replace(/ - CompanyName/i, '').replace(/The /i, '');

String manipulation using javascript

I am working on some string manipulations using javascript.I have a senario where i need to do a search in the string and remove certain words.
Here is my senario:
When i click 'Click me' it should look for the word in the input from the string variable,
and if matching found it should remove that word from the input.
Here is my sepecial senario, while removing the word from the input, it should remove the : and the integer value and comma (if available) which is there before the matching word.
In my example input is 1:first user,2:second user in the text box
i need the output as 2:second user
How can i achive this
<input id='textinput' type='text' value='1:first user,2:second user'></input>
<div class='click'>Click me</div>
$(document).ready(function () {
$(".click").click(function () {
var string = 'first user';
$('#textinput').val().replace(/string/g, '');
});
});
i have created a fiddle http://jsfiddle.net/h9D5W/
EDIT
here my variable string contains only user names i can't append id's with user names for example 1:first user, so the exact match will not be there in the string variable.
I have removed the starting digits, underscore and ending comma.
$(document).ready(function () {
$(".click").click(function () {
var string = 'first user';
var re = new RegExp('\\d:*'+string+',*',"g");
var text = $('#textinput').val().replace(re, '');;
$('#textinput').val(text);
});
});
Check the demo
http://jsfiddle.net/yKfur/1/
In your JavaScript code, string is a variable. You'd need to initiate the RegExp class to generate the pattern:
Also, please refrain from using variable name like string. It's the name of a global object.
var s = 'first user';
var x = $( '#textinput' ).val().replace(new RegExp(s, 'g'), '');
// use the new variable x as you wish
You should use RegExp, You need to initialize it with string variable.
Use
$(".click").click(function () {
var string = 'first user';
var re = new RegExp(string,"g"); //initialize RegExp
var text = $('#textinput').val().replace(re, ''); //Get replaced text
$('#textinput').val(text); //Reset its value
});
DEMO
EDIT
here i cant use 1:first user in the variable
$(".click").click(function () {
var arr = $('#textinput').val().split(','); //Here used split method to split string ',' as deliminator
$('#textinput').val(arr[arr.length - 1]);
});
DEMO
You can use a regular expression like:
var text = '1:first user,2:second user,3:third user';
var s = 'first user';
var re = new RegExp('^\\d+:' + s + ',?|,\\d+:' + s + '\\b');
text.replace(re, '') // '2:second user,3:third user'
I'm sure there's a shorter one though.
I have updated your fiddle
first, i split your string into array
var inputArr = ($('#textinput').val()).split(',');
so i can check each set of words using for loop,
for (i = 0; i < inputArr.length; i++) {
if (inputArr[i].indexOf(string) == -1) {
newStr = newStr + inputArr[i] + ',';
}
}
then i set the new value using substring to eliminate the last comma appended.
$('#textinput').val(newStr.substring(0, newStr.length - 1));

url.replace with multiple replacements?

I've currently got the following to remove spaces and replace them with a hyphen.
How can I go about replacing a space with a hyphen and a dot with nothing and keep it in the same variable?
url = url.replace(/\s/g, '-');
url = url.replace(/\s/g, '-').replace(/\./g, ''); might do it.
I use this:
// This little gadget does replace for all not just first occurence like the native javascript function.
String.prototype.replaceAll = function(strTarget, strSubString){
var strText = this;
var intIndexOfMatch = strText.indexOf(strTarget);
while (intIndexOfMatch != -1){
strText = strText.replace(strTarget, strSubString);
intIndexOfMatch = strText.indexOf(strTarget);
}
return(strText);
}

remove first match from string in javascript and jquery

I have string like this 'set , many, like, see, what'
when i create this string i also create div with linked element
<div>
set
many
like
...
</div>
and also create hidden input with 'set , many, like, see, what' value ... when we click on linked element we have string of link ( example: set )
how remove first match of string and strip it from hidden input?
ps: i said first match because one element can repeat
Where link is a reference to one of the links, theString is a reference to your string, and hidden is a reference to your hidden input control, you can do something like this:
link.onclick = function(e)
{
var expr = new RegExp("\b" + this.innerHTML + "\b(, ?)?");
theString = theString.replace(expr, "");
hidden.value = theString;
}
var anchors = document.getElementById('container').getElementsByTagName('a'),
hiddenInput = document.getElementById('hidden');
for (var i = 0, anchorsLength = anchors.length; i < anchorsLength; i++) {
var anchor = anchors[i];
anchor.onclick = function() {
var term = anchor.innerHTML;
hiddenInput.value = hiddenInput
.value
.replace(new RegExp(term + ',\s?'), '');
}
}
This code allows you to click one of those anchors, in which it will remove the first occurrence of the anchor's text node, and the , and any optional whitespace character.

Can I use a regex and foo.replace() to substitute occurances of a string that aren't in anchor tag?

I'm trying to use JavaScript to replace target text with a hyperlinked version of the target text. Generally speaking, this is the function in question:
function replace_text_in_editor(target_text, target_type, target_slug) {
//if target_text was "Google", then the replacement_text might be "Google
var replacement_text = get_replacement_text(target_text, target_type, target_slug);
if(typeof replacement_text != undefined && replacement_text != '') {
var content = '';
content = jQuery( "#content" ).val();
content = content.replace(target_text,replacement_text)
if(content != '') {
jQuery( "#content" ).val(content);
}
}
}
I've tried a couple permutations of the following line, which I'd like to alert to only replace text that's not already hyperlinked.
var regex = "/" + target_text + "/";
content = content.replace(regex,replacement_text);
Example attempt:
var regex = "/^(<a.*?>)" + target_text + "^(<\/a>)/";
Can someone please correct me with a regex showing how I should be doing this? No need to explain what the regex does step by step, as I can infer that from the design. Thank you!
I think you want this but I'm not sure that I compeletly understand.
If you use RE to find the text you can assign it to group $1 by putting () around it (in this case "Google").
Then when you go to replace it you build the expression with that group assignment id $1
\<a href="$1\.com"\>$1\<\/a\>

Categories

Resources