[英]Javascript: How to cut a specific part of a string?
情况:
我需要剪切字符串的特定部分。 该部分的长度和内容并不总是相同的。
我唯一知道的是它将始终以: <style>
开头并以: </style>
中间的所有内容都必须删除(包括样式标签)。
问题:
如何仅知道字符串的开始和结尾来剪切字符串的特定部分?
您可以使用javascript直接操作DOM,而无需使用正则表达式或jquery。 您需要选择目标元素/类/ id的父元素,然后删除子元素。
HTML:
<html>
<head>
<style>
body {color:blue;}
</style>
</head>
<body>
JavaScript的:
var text = document.querySelectorAll("style")[0];
text.parentNode.removeChild(text);
假设您有以下string
var str = '<style>I am a style</style>';
var res = str.replace("<style>", "").replace("</style>", "");
alert(res);
获取零件字符串:
theString = 'asdfasdf<style>aaaaaaaaaaaaaa</style>bbbbbbbb'
targetString= theString.replace(/<\/style>/ig,'<style>').split('<style>')[1];
删除整个字符串:
theString = 'asdfasdf<style>aaaaaaaaaaaaaa</style>bbbbbbbb'
targetString= theString.replace(/<style>.*<\/style>/ig,'');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.