javascript jquery regexp replace - javascript

I'm trying to create a dynamic searchbar and i need help.
Right now im trying to replace a string with another string but i cant seem to succeed.
Im getting input from the user:
var location_keyword = $("#si_user_location").val();
Now i would like to replace a whitespace " " with a "|" to use this in my regexp as OR.
For example if the user wrote "Turkey Alanya", i want it to be "Turkey|Alanya" so that the search hits for both Turkey OR Alanya.
i tried something like this but it didnt work
var location_keyword = $("#si_user_location").val();
location_keyword.replace(" ","|");
var regexp_loc = new RegExp(location_keyword, "i");
i used to do this in PHP before with expressions such as:
preg_replace('/'.preg_quote($keyword).'/i', "<span>$0</span>", $string)
and i could replace strings caseinsensetive like this, how can i do this in js?
I used the last expression in PHP to highlight the keyword in the results, which i would like to do aswell in js.
hope i can get some help, thanks in advance! :)
best of regards,
alexander

There are two problems with the use of replace on this line:
location_keyword.replace(" ","|");
It does not modify the string - it returns a new string. You need to reassign the result of the call to the original variable otherwise you won't see the changed string.
It only replaces the first occurrence unless you use a regular expression with the g (global) flag.
Try this instead:
location_keyword = location_keyword.replace(/ /g, '|');

Try this:
location_keyword = location_keyword.replace(/\s+/,"|");

This should work fine:
location_keyword.replace(/ /g,"|");
Hope this helps! :)

Related

Removing elements of string before a specific repeated character in it in javascript

I'm trying to remove from my string all elements before an specific character which is repeated several times in this way:
let string = http://localhost:5000/contact-support
thus I´m just trying to remove everything before the third /
having as result:contact_support
for that i just set:
string.substring(string.indexOf('/') + 3);
Bust guess thats not the correct way
Any help about how to improve this in the simplest way please?
Thanks in advance!!!
It seems like you want to do some URL parsing here. JS brings the handful URL utility which can help you with this, and other similar tasks.
const myString = 'http://localhost:5000/contact-support';
const pathname = new URL(myString).pathname;
console.log(pathname); // outputs: /contact-support
// then you can also remove the first "/" character with `substring`
const whatIActuallyNeed = pathname.substring(1, pathname.length);
console.log(whatIActuallyNeed); // outputs: contact-support
Hope This will work
string.split("/")[3]
It will return the sub-string after the 3rd forward slash.
You could also use lastIndexOf('/'), like this:
string.substring(string.lastIndexOf('/') + 1);
Another possibility is regular expressions:
string.match(/[^\/]*\/\/[^\/]*\/(.*)/)[1];
Note that you must escape the slash, since it is the delimiter in regular expressions.
string.substring(string.lastIndexOf('/')+1) will also do the job if you are looking to use indexOf function explicitly.

Use only one of the characters in regular expression javascript

I guess that should be smth very easy, but I'm stuck with that for at least 2 hours and I think it's better to ask the question here.
So, I've got a reg expression /&t=(\d*)$/g and it works fine while it is not ?t instead of &t in url. I've tried different combinations like /\?|&t=(\d*)$/g ; /\?t=(\d*)$|/&t=(\d*)$/g ; /(&|\?)t=(\d*)$/g and various others. But haven't got the expected result which is /\?t=(\d*)$/g or /&t=(\d*)$/g url part (whatever is placed to input).
Thx for response. I think need to put some details here. I'm actually working on this peace of code
var formValue = $.trim($("#v").val());
var formValueTime = /&t=(\d*)$/g.exec(formValue);
if (formValueTime && formValueTime.length > 1) {
formValueTime = parseInt(formValueTime[1], 10);
formValue = formValue.replace(/&t=\d*$/g, "");
}
and I want to get the t value whether reference passed with &t or ?t in references like youtu.be/hTWKbfoikeg?t=82 or similar one youtu.be/hTWKbfoikeg&t=82
To replace, you may use
var formValue = "some?some=more&t=1234"; // $.trim($("#v").val());
var formValueTime;
formValue = formValue.replace(/[&?]t=(\d*)$/g, function($0,$1) {
formValueTime = parseInt($1,10);
return '';
});
console.log(formValueTime, formValue);
To grab the value, you may use
/[?&]t=(\d*)$/g.exec(formValue);
Pattern details
[?&] - a character class matching ? or &
t= - t= substring
(\d*) - Group 1 matching zero or more digits
$ - end of string
/\?t=(\d*)|\&t=(\d*)$/g
you inverted the escape character for the second RegEx.
http://regexr.com/3gcnu
I want to thank you all guys for trying to help. Special thanks to #Wiktor Stribiżew who gave the closest answer.
Now the piece of code I needed looks exactly like this:
/[?&]t=(\d*)$/g.exec(formValue);
So that's the [?&] part that solved the problem.
I use array later, so /\?t=(\d*)|\&t=(\d*)$/g doesn't help because I get an array like [t&=50,,50] when reference is & type and the correct answer [t?=50,50] when reference is ? type just because of the order of statements in RegExp.
Now, if you're looking for a piece of RegExp that picks either character in one place while the rest of RegExp remains the same you may use smth like this [?&] for the example where wanted characters are ? and &.

Change Multi line strings to Single line

Hi I have some text in following format,
683101,
682303,
682302,
682315,
683581,
686667,
682008,
683572,
683573,
682313,
686672,
683545 etc....
Each line break'ed into next line with "Enter". I have nearly 2000 lines of text like this. i want o display the above string to a single line like this.
683101,
682303,
682302,
682315,
683581,
686667,
682008,
683572,
683573,
682313,
686672,
683545,
686672,
683545 etc..
I think there is some tweak options in CSS for doing this. Is there a way in JavaScript to do this? Actually it is not a requirement for me, am just curious to know how it is done.
Edit:
In My text editor it looks like this,
When i try to run it, this is what i get.
Thats why i want to remove the enter, multiline.......
You can use Regular expression to remove all the linebreaks and replace them using space.
str = str.replace(/\n/g, ' ');
Here, \n will match all the line-breaks, and replace them by space
I have a simple way for this. You can do this without extra code. Just write like this -
var str = "12345,\
234234,\
234324,\
234324,\
234324,\
234234";
now just add a slash
Ok, If you don't want to use the above method then use another plan is -
take inside an array and after that use the join method
var str = [12345,
234234,
234324,
234324,
234324,
234234];
str.join(",");
If we are using ES6, Then we have an elegant way to do this using Backtick -
var str = `12345,
234234,
234324,
234324,
234324,
234234`;
Since your data is already comma separated, you can try to add "[" to the beginning and append " ].toString().replace(/\n/g," ") " to the end of your data to get a single line string like this:
[683101,
682303,
682302,
682315,
683581,
686667,
682008,
683572,
683573,
682313,
686672,
683545].toString().replace(/\\n/g," ")
then you get:
"683101,682303,682302,682315,683581,686667,682008,683572,683573,682313,686672,683545"
I hope this helps :)
If all you want is to put those values in one line then, you can set those values as the value of a textarea field. This will allow you to read all those values into a javascript string. Afterward you can apply the regular expression that Tushar suggested.
See the code segment below:
<textarea id="content">
683101,
682303,
682302,
682315,
683581,
686667,
682008,
683572,
683573,
682313,
686672,
683545
</textarea>
Here is the javascript:
var content = $('#content').val();
var content = content.replace(/\n/g, ' ');
console.log(content);

Is it possible to cut off the beginning of a string using regex?

I have a string which contains a path, such as
/foo/bar/baz/hello/world/bla.html
Now, I'd like to get everything from the second-last /, i.e. the result shall be
/world/bla.html
Is this possible using a regex? If so, how?
My current solution is to split the string into an array, and join its last two members again, but I'm sure that there is a better solution than this.
For example:
> '/foo/bar/baz/hello/world/bla.html'.replace(/.*(\/.*\/.*)/, "$1")
/world/bla.html
You can also do
str.split(/(?=\/)/g).slice(-2).join('')
> '/foo/bar/baz/hello/world/bla.html'.match(/(?:\/[^/]+){2}$/)[0]
"/world/bla.html"
Without regular expression:
> var s = '/foo/bar/baz/hello/world/bla.html';
> s.substr(s.lastIndexOf('/', s.lastIndexOf('/')-1))
"/world/bla.html"
I think this will work:
var str = "/foo/bar/baz/hello/world/bla.html";
alert( str.replace( /^.*?(\/[^/]*(?:\/[^/]*)?)$/, "$1") );
This will allow for there being possibly only one last part (like, "foo/bar").
You can use /(\/[^\/]*){2}$/ which selects a slash and some content twice followed by the end of the string.
See this regexplained.

Match URL's which do NOT have a specific prefix

i match image urls inside a string with the following regular expression in javascript:
/\b(https?|ftp|file):\/\/[\-A-Z0-9+&##\/%?=~_|!:,.;]*[\-A-Z0-9+&##\/%=~_|]?(\.(jpe?g|png|gif))/ig
with the String.replace function, i wrap all matches inside an -tag.
in a second step i'd like to match all urls, which do not have the above file extensions as prefix. my first intention was to use the ?!-operator like this:
/\b(https?|ftp|file):\/\/[\-A-Z0-9+&##\/%?=~_|!:,.;]*[\-A-Z0-9+&##\/%=~_|]?(?!\.(jpe?g|png|gif))/ig
unfortunatly, this does no work. tried different variations of this expression, but with now results.
thanks for any help in advance,
manuel
Since you're asking about javascript, I think something like this could help :
var url_re = "\\b(https?|ftp|file):\\/\\/[\\-A-Z0-9+&##\\/%?=~_|!:,.;]*[\\-A-Z0-9+&##\\/%=~_|]?"
var re = new RegExp( "^(?!.*"+url_re+"\.(jpe?g|png|gif)).*"+url_re+"\.[a-z0-9_]+" , 'gi' )

Categories

Resources